简体   繁体   English

Typescript:`let result:{[key:T [K]]:T} = {};`不起作用,如何基于泛型键入对象?

[英]Typescript: `let result: { [key: T[K]]: T } = {};` is not working, how can I type my object based on generics?

I want to type a simple function called keyBy . 我想键入一个称为keyBy的简单函数。

What this function do is to convert an array of objects into object based on provided 'key string': 此函数的作用是根据提供的“关键字字符串”将object array of objects转换为object

const arr = [{ name: 'Jason', age: 18 }, { name: 'Amy', age: 25 }];

console.log(keyBy(arr, 'name'));

// => { 'Jason': { name: 'Jason', age: 18 }, 'Amy': { name: 'Amy', age: 25 } }

Now, here is a simple correct javascript implementation without typescript. 现在,这是一个没有打字稿的简单正确的javascript实现。

function keyBy(arr, key) {
  let result = {};

  arr.forEach(obj => {
    result[obj[key]] = obj;
  });

  return result;
}

Right now, below is my typescript version of keyBy (not compiling): 现在,下面是我的keyBy打字稿版本(未编译):

function keyBy<T, K extends keyof T>(arr: T[], key: K): { [key: T[K]]: T } {

  // typescript yells: An index signature parameter type must be 'string' or 'number'.

  let result: { [key: T[K]]: T } = {};

  arr.forEach(item => {
    result[item[key]] = item;
  });

  return result;
}

Here is the screenshot of my VSCode: 这是我的VSCode的屏幕截图:

在此处输入图片说明

How can I type this keyBy function correctly? 如何正确键入此keyBy函数?

In think you can do in some other way too: 在思想上,您也可以通过其他方式进行操作:

export type Omit<A extends object, K extends keyof A> = Pick<A, Exclude<keyof A, K>>

type KeyOf<T extends Array<any>> = { [K: string]: Omit<T[number], 'name'> };

type Result = KeyOf<[{ name: 'a', attr: 42 }, { name: 'b', attr: 42}, {name: 'c', attr: 42}]>

Omit util will return interface without one key, in this case 'name'. Omit util将返回没有一个键的接口,在这种情况下为“名称”。

T[number] when T extends Array will return X T[number]扩展时的T[number]数组将返回X

And K always be a string because if ordinary object. 而且K总是一个字符串,因为如果是普通对象。

playground 操场

To use named key properties, you need in rather than : : 要使用名为关键属性,需要in而非:

{ [key in K]: T }

You also need to use K , which is a string union type of property names, not T[K] , which is the value of the property. 您还需要使用K ,它是属性名称的字符串联合类型,而不是T[K] ,它是属性的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 打字稿无法为具有 hasOwnProperty 类型缩小的对象键赋值 - Typescript can't assign value to object key with hasOwnProperty type narrowing 打字稿:类型“{}”不能指定为“选择”类型 <T, K> &#39;,如何正确输入javascript`pick`功能? - Typescript: Type '{}' is not assignable to type 'Pick<T, K>', how do I type javascript `pick` function correctly? TypeScript:对于这个 function,如何将类型显式传递给 generics - TypeScript: How can I explicitly pass in the type to the generics for this function 打字稿“ Immutable.Map <K, T> 作为对象” - Typescript “Immutable.Map<K, T> as Object” 打字稿中的泛型-未定义T - Generics in Typescript - Undefined T Typescript | 从 object 中提取所有具有 T 类型值的键名 - Typescript | extract from an object all key names with values of type T 打字稿打字不按预期工作,我该如何解决这个问题? - typescript typing isn't working as intended, how can I solve this? Typescript对象索引器和与索引器类型不匹配的键 - Typescript object indexer and key that doesn't match indexer type Typescript 我无法在 object 中建立索引,它可能有很多 object 类型 - Typescript I can't index in the object ,which has many maybe object type 如何修复嵌套对象的“类型&#39;K扩展X [T]?keyof K:从不&#39;不能用于索引类型”? - How to fix "Type 'K extends X[T] ? keyof K : never' cannot be used to index type" for nested object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM