【问题标题】:How do I pass this Generic type an argument in TypeScript如何在 TypeScript 中将此通用类型作为参数传递
【发布时间】:2021-11-11 01:11:08
【问题描述】:

我无法正确形成类型的参数。

这是我的界面

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();

论证应该是什么样的?一旦我正确地制定了响应,我将如何访问它?

冒着添加不必要的代码并被遗忘的风险,我会到此结束!

谢谢!

【问题讨论】:

    标签: reactjs typescript typescript-generics use-state


    【解决方案1】:

    您需要使用类型提示泛型:

    // Define your data type
    type MyDataType = number;
    
    const [data, setData] = useState<IAssetGetManyResponseDto<MyDataType>>()
    

    【讨论】:

    • 我希望对世界有所帮助的后续行动 - 如果我有响应类型 export interface IAssetResponseDto { id: string | null; name: string | null; type: string | null; url: string | null; // metadata: IMetadataObj| null; tags: Array&lt;string&gt; | null; thumbnailImageURL: string | null; createdAt: number | null; updatedAt: number | null; } 并且我暗示像这样的泛型 useState&lt;IAssetGetManyResponseDto&lt;IAssetResponseDto&gt;&gt;() 那么我实际上告诉 useState 使用什么形状?不知道如何使用参数来访问 items [] 对象数组
    • 非常感谢!顺便说一句,如果您正在寻找另一个绿色复选标记,您可能可以轻松成为我在更大问题中的英雄,发布在这里stackoverflow.com/questions/69213626/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多