【问题标题】:TypeScript: Convert Array to ObjectTypeScript:将数组转换为对象
【发布时间】:2022-09-27 19:30:01
【问题描述】:

我正在尝试为将数组转换为对象的函数编写泛型类型,如下所示:

type ObjType = { id: number; name: string; status: string };
const zzx: ObjType[] = [
  {
    id: 1,
    name: \"A\",
    status: \"a\"
  },
  {
    id: 2,
    name: \"B\",
    status: \"b\"
  },
  {
    id: 3,
    name: \"C\",
    status: \"c\"
  }
];

function arrayToObject<T>(
  arr: T[],
  key: string | number
): Record<string | number, T> {
  const result: Record<string, T> = {};
  for (const item of arr) {
    const value = item[key as keyof typeof T];
    result[value] = item;
  }
  return result;
}

const xx = arrayToObject<ObjType>(zzx, \"id\");

我在某处读到泛型类型可以作为 <> 括号中的参数传递。 但是,我在从函数调用传递的函数中看不到类型(ObjType)。 并且还低于item[key as keyof typeof T]; 行中的错误

Element implicitly has an \'any\' type because expression of type \'string | number | symbol\' can\'t be used to index type \'unknown\'.
  No index signature with a parameter of type \'string\' was found on type \'unknown\'.

有人可以告诉我我做错了什么吗?

    标签: reactjs typescript


    【解决方案1】:

    传递通用类型参数时,它会检查您的用法,而不是通用类型实现,即类型的使用在验证类型本身时根本不重要!

    您可以稍微自定义您的 Generic 类型以获得可以正常工作的东西, 请记住,没有一个正确的解决方案,它始终取决于您的需求!

    查看this possible solution

    首先,为简单起见,我添加了这些类型

    type KType = string | number
    type GeneratedObj<T> = Record<KType, T>
    

    请注意,您返回的是result,因此它应该与函数返回类型相同

    对于函数类型,我将其更改为:

    function arrayToObject<T extends Record<KType, unknown>>(
      arr: T[],
      key: KType
    ): GeneratedObj<T> {
    ...
    ...
    

    您期望T 有一个密钥,应该在您需要传递stringnumber 的地方使用,然后您可以告诉打字稿该信息,这个T 扩展了这个形状,具有string | number 类型键的对象, 关于值,如果你知道它的类型,你可以输入它,如果它可以是任何东西,你可以将其保留为unknown

    现在你可以直接做:

    const value = item[key];
    

    但是因为T props 的值现在定义为unknown 我们需要在下一行转换value 的类型:

    result[value as KType] = item;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-20
      • 2019-05-16
      • 1970-01-01
      • 1970-01-01
      • 2021-11-20
      • 2020-06-22
      • 2021-11-04
      • 1970-01-01
      相关资源
      最近更新 更多