类似于:
How to infer a typed array from a dynamic key array in typescript?
我希望键入一个通用对象,该对象接收任意键到查找值的映射,并返回具有键入值的相同键(如键入的 _.mapValues)。
从对象中获取单一类型属性的能力已被记录并有效。对于数组,您需要将重载硬编码到类型化元组,但对于对象,我收到“重复字符串索引签名”错误。
export interface IPerson {
age: number;
name: string;
}
const person: IPerson = {
age: 1,
name: ""
}
function getProperty<T, K extends keyof T>(o: T, name: K): T[K] {
return o[name];
}
const a = getProperty(person, 'age');
// a: number
const n = getProperty(person, 'name');
// n: string
function getProperties<T, K extends keyof T>(obj: T, keys: { [key: string]: K }) {
const def: { [key: string]: T[K] } = {};
return Object.entries(keys).reduce((result, [key, value]: [string, K]) => {
result[key] = getProperty(obj, value);
return result;
}, def);
}
const { a2, n2 } = getProperties(person, {
a2: 'name',
n2: 'age'
});
// Result:
// {
// a2: string | number,
// n2: string | number
// }
// What I'm looking for:
// {
// a2: string,
// n2: number'
// }
如何使用 typescript 实现这一点?
最佳答案
只要它在运行时工作,您可以告诉 TypeScript 如何使用 mapped types 重命名键:
type RenameKeys<T, KS extends Record<keyof KS, keyof T>> = {[K in keyof KS]: T[KS[K]]};
function getProperties<T, KS extends Record<keyof KS, keyof T>>(
obj: T,
keys: KS
): RenameKeys<T, KS> {
const def = {} as RenameKeys<T, KS>;
return (Object.entries(keys) as Array<[keyof KS, any]>)
.reduce((result, [key, value]) => {
result[key] = getProperty(obj, value);
return result;
}, def);
}
这在类型系统中的行为应该与您预期的一样。亮点:keys
的类型被赋予一个名为 KS
的类型参数,它被限制为 Record<keyof KS, keyof T>
,这或多或少意味着“我不在乎键是什么,但属性类型需要是来自 T
的键”。然后,RenameKeys<T, KS>
遍历 KS
的键并从 T
中提取属性类型与他们有关。
最后,我需要做一些类型断言... def
是RenameKeys<T, KS>
. value
的类型在 [key, value]
我刚做了any
,因为类型系统很难验证 result[key]
将是正确的类型。所以这是对实现类型安全的一种捏造......但是 getProperties()
的调用者应该高兴:
const {a2, n2} = getProperties(person, {
a2: 'name',
n2: 'age'
});
// a2 is string, n2 is number.
关于typescript - 如何使用 typescript 中的查找来推断类型化的 mapValues?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50822693/