我目前在理解类型记录映射类型时遇到了一些困难,他们列出了“键重映射”是可能的,但是当实际使用数组时,它只是Type '"key"' cannot be used to index type 'A[E]'中的错误。
注意:这是一个类型问题,而不是运行时问题。
示例代码:
interface ListEntry {
key: string;
prop: string;
}
type MapListEntryArrayToRecord<A extends ListEntry[]> = {
// Error "Type '"key"' cannot be used to index type 'A[E]'"
[E in keyof A as A[E]['key']]: A[E]['prop'];
};
const input: ListEntry[] = [
{ key: 'key1', prop: 'Prop1' },
{ key: 'key2', prop: 'Prop2' },
];
function someFunction<List extends ListEntry[]>(list: List): MapListEntryArrayToRecord<List> {
// some implementation
const ret: Record<string, ListEntry['prop']> = {};
for (const { key, prop } of list) {
ret[key] = prop;
}
return ret as MapListEntryArrayToRecord<List>;
}
const mapped = someFunction(input);
// expecting intellisense for all available keys
mapped;
// example of what i would expect
const expectedOutput = {
key1: 'Prop1',
key2: 'Prop2',
};
// expecting intellisense for all available keys
expectedOutput;PS:我试图寻找一个答案,但没有找到任何打字的例子,如何做到这一点。
发布于 2022-07-27 16:19:22
这里有一些问题。
首先是input对象。如果使用显式类型,则将丢失有关分配给它的对象的特定值的所有信息。因此,我们必须删除类型并添加as const。
const input = [
{ key: 'key1', prop: 'Prop1' },
{ key: 'key2', prop: 'Prop2' },
] as const;使用as const将数组转换为readonly。我们必须修改泛型类型以同时接受普通数组和readonly数组。
type MapListEntryArrayToRecord<A extends readonly ListEntry[]> = {
/* ... */
};
function someFunction<List extends readonly ListEntry[]>(list: List): MapListEntryArrayToRecord<List> {
/* ... */
}现在回到你原来的问题。TypeScript在知道A[keyof A]有一个key属性时有问题。这归结为这样一个事实,即使用泛型类型和类似表达式的键索引的泛型类型通常不会被编译器完全计算。
因此,我们必须通过显式检查来提醒TypeScript该属性存在。
type MapListEntryArrayToRecord<A extends readonly ListEntry[]> = {
[E in keyof A as A[E] extends { key: infer K extends string } ? K : never]:
A[E]['prop'];
};https://stackoverflow.com/questions/73140386
复制相似问题