【发布时间】:2018-08-26 16:03:38
【问题描述】:
我如何使用泛型来强制一个值的类型为特定类型?
// An example array
const testArr = [
{
id: 3,
name: 'Spaghetto', // NOTE: Type 'string' here
shouldNotWork: 3.14, // NOTE: Type 'number' here
},
{
id: 5,
name: 'Bread',
shouldNotWork: 3.14,
},
];
这是我试图成为我的映射函数,但我必须附加 as V2 以使 TS 不会抱怨:/
type Mapping<T, U> = (val: T, i: number, arr: T[]) => U;
interface Option<T> {
value: T;
label: string; // <- NOTE: Type string is required
}
const typeToOption = <
T,
K1 extends keyof T,
K2 extends keyof T,
V2 extends T[K2] & string // <- NOTE: 'string' union here to match
>(
valueK: K1,
labelK: K2,
): Mapping<T, Option<T[K1]>> => (item: T): Option<T[K1]> => ({
value: item[valueK],
label: item[labelK] as V2,
});
我希望 TS 允许我这样做
const result = testArr.map(typeToOption('id', 'name'));
...但不是这个
const result = testArr.map(typeToOption('id', 'shouldNotWork'));
如何让 TS 抱怨后者?
【问题讨论】:
标签: typescript typescript-generics