【发布时间】:2018-11-19 09:09:36
【问题描述】:
我希望键入一个通用对象,并让该对象的属性返回一个类型化数组。从对象获取单一类型属性的能力已记录并有效,但是我无法让它与数组一起使用。似乎是“联合类型”。
// from the documentation
// @ http://www.typescriptlang.org/docs/handbook/advanced-types.html
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
const getProperties = <T>(obj: T, keys: Array<keyof T>) => keys.map((arg) => getProperty(obj, arg));
const [a2, n2] = getProperties(person, ['name', 'age']);
// result:
// a2: string | number
// n2: string | number
// what i want:
// a2: string
// n2: number
【问题讨论】:
标签: typescript