[英]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总是一个字符串,因为如果是普通对象。
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.