如何在泛型函数中从参数类型推断返回类型?

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有可能吗?

更新

在github上已经有一个已经打开的问题,它涵盖了我的例子.因此,目前的答案是"不,但未来可能".

Eya*_*sSH 4

您可以在此处使用函数重载:

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)