如何在 TypeScript 中将此通用类型作为参数传递
How do I pass this Generic type an argument in TypeScript
我在正确形成类型参数时遇到问题。
这是我的界面
export interface IAssetGetManyResponseDto<T> {
items: T[];
totalCount: number;
}
在我的应用程序中,我想将参数传递给 useState 挂钩,并使用 useState 和 useEffect 获取一些具有 IAssetGetManyResponseDto
.
类型响应的数据
这是我尝试将类型传递给参数的方式以及我正在尝试做的事情的更大背景
import { useState, useEffect } from 'react';
import { getAllAssets } from '../api/api';
import { NewAssetTable } from "../components/NewAssetTable"
import { IAssetGetManyResponseDto } from '../types/types';
export const AssetManagementTable = () => {
const [data, setData] = useState<IAssetGetManyResponseDto>()
const getAssets = async () => {
const assets = await getAllAssets();
console.log(data)
console.log(assets)
setData(assets)
}
useEffect(() => {
getAssets()
}, []);
return (
<div>
<NewAssetTable items={data.items} />
</div>
);
};
错误:
Generic type 'IAssetGetManyResponseDto<T>' requires 1 type argument(s). TS2314
8 | export const AssetManagementTable = () => {
9 |
> 10 | const [data, setData] = useState<IAssetGetManyResponseDto>()
| ^
11 |
12 | const getAssets = async () => {
13 | const assets = await getAllAssets();
论点应该是什么样的?一旦我正确地制定了响应,我将如何访问响应?
冒着添加不必要的代码并被遗忘的风险,我就此结束!
谢谢!
您需要使用类型提示泛型:
// Define your data type
type MyDataType = number;
const [data, setData] = useState<IAssetGetManyResponseDto<MyDataType>>()
我在正确形成类型参数时遇到问题。
这是我的界面
export interface IAssetGetManyResponseDto<T> {
items: T[];
totalCount: number;
}
在我的应用程序中,我想将参数传递给 useState 挂钩,并使用 useState 和 useEffect 获取一些具有 IAssetGetManyResponseDto
.
这是我尝试将类型传递给参数的方式以及我正在尝试做的事情的更大背景
import { useState, useEffect } from 'react';
import { getAllAssets } from '../api/api';
import { NewAssetTable } from "../components/NewAssetTable"
import { IAssetGetManyResponseDto } from '../types/types';
export const AssetManagementTable = () => {
const [data, setData] = useState<IAssetGetManyResponseDto>()
const getAssets = async () => {
const assets = await getAllAssets();
console.log(data)
console.log(assets)
setData(assets)
}
useEffect(() => {
getAssets()
}, []);
return (
<div>
<NewAssetTable items={data.items} />
</div>
);
};
错误:
Generic type 'IAssetGetManyResponseDto<T>' requires 1 type argument(s). TS2314
8 | export const AssetManagementTable = () => {
9 |
> 10 | const [data, setData] = useState<IAssetGetManyResponseDto>()
| ^
11 |
12 | const getAssets = async () => {
13 | const assets = await getAllAssets();
论点应该是什么样的?一旦我正确地制定了响应,我将如何访问响应?
冒着添加不必要的代码并被遗忘的风险,我就此结束!
谢谢!
您需要使用类型提示泛型:
// Define your data type
type MyDataType = number;
const [data, setData] = useState<IAssetGetManyResponseDto<MyDataType>>()