And*_*aev 6 typescript conditional-types typescript2.8
这是一些条件类型的代码
class A {
public a: number;
}
class B {
public b: number;
}
type DataType = "a" | "b";
type TData<T extends DataType> =
T extends "a" ? A :
T extends "b" ? B :
never;
Run Code Online (Sandbox Code Playgroud)
现在我想使用条件类型作为从函数参数到其返回类型的链接.我尝试以不同的方式实现这一点而没有结果:
function GetData<T extends DataType>(dataType: T): TData<T> {
if (dataType == "a")
return new A();
else if (dataType == "b")
return new B();
}
Run Code Online (Sandbox Code Playgroud)
什么是正确的语法?TypeScript 2.8有可能吗?
更新
您可以在此处使用函数重载:
function GetData(dataType: "a"): A;
function GetData(dataType: "b"): B;
function GetData(dataType: DataType): A | B {
if (dataType === "a")
return new A();
else if (dataType === "b")
return new B();
}
const f = GetData('a'); // Inferred A
const g = GetData('b'); // Inferred B
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
310 次 |
| 最近记录: |