【发布时间】:2019-11-06 02:09:31
【问题描述】:
在下面的 sn-p 中,最后两条看似等效的行显然不是。我想编写我的函数定义,既不出错,又返回(string | number)[]。有什么想法吗?
function keyableValues<T extends Record<any, keyof any>>(o: T): T[keyof T][] {
const values: T[keyof T][] = [];
for (const key of Object.getOwnPropertyNames(o)) {
values.push(o[key as keyof T]);
}
return values;
};
interface O {
a: string;
b: number;
}
let asInterface: O = { a: 'hi', b: 2 };
const notAsInterface = { a: 'hi', b: 2 };
keyableValues(asInterface); // <- typing error, returns (string | number | symbol)[]
keyableValues(notAsInterface); // <- no error, returns (string | number)[]
倒数第二行的错误是:
“O”类型的参数不能分配给“记录”类型的参数。
类型“O”中缺少索引签名。(2345)
Here it is in the typescript playground.
编辑
请注意,这是一个简化的示例。保持对可分配给keyof any 的值的限制非常重要。我真正的用例是将集合中的值映射到新对象的键的函数:
function mapAsKeys<T extends Record<any, keyof any>, V>(
object: T,
iteratee: ObjectIteratee<T, V>,
): Record<T[keyof T], V>;
【问题讨论】:
标签: typescript