我正在尝试编写一个函数,它在给定枚举值的情况下返回特定类型。 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
。
最佳答案
我不知道你是否可以接受,但是function overloads似乎工作。如果您决定采用此解决方案,则需要将 interface Type
替换为每种情况的特殊重载签名。
interface A {
a: string;
}
interface B {
b: string;
}
enum DataType {
a = 'a',
b = 'b',
}
function test(value: DataType.a): A;
function test(value: DataType.b): B;
function test(value: DataType): A | B {
switch (value) {
case DataType.a:
return {a: 'testA'};
case DataType.b:
return {b: 'testB'};
}
}
关于switch 语句中的 Typescript 特定类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66798083/