我正在尝试编写一个函数,该函数在给定枚举值的情况下返回特定类型。 Typescript 无法识别 switch 和 if 语句中的属性。
interface A {
a: string;
}
interface B {
b: string;
}
enum DataType {
a = 'a',
b = 'b',
}
interface Type {
[DataType.a]: A;
[DataType.b]: B;
}
function test<T extends keyof Type>(type: T): Type[T] {
switch (type) {
case DataType.a:
return {a: 'test'}; // <--- no error, but TS doesn't recognize the property
}
}
使用 Typescript 4.2.3
。