gpt4 book ai didi

typescript - 如何从泛型函数中的参数类型推断返回类型?

转载 作者:搜寻专家 更新时间:2023-10-30 20:40:38 25 4
gpt4 key购买 nike

这是一些带有条件类型的代码

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;

现在我想使用条件类型作为从函数参数到它的返回类型的链接。我尝试以不同的方式实现这一目标,但没有结果:

function GetData<T extends DataType>(dataType: T): TData<T> {
if (dataType == "a")
return new A();
else if (dataType == "b")
return new B();
}

什么是正确的语法? TypeScript 2.8 可以吗?

更新

已经有一个 opened issue on github这涵盖了我的例子。所以目前的答案是“不,但将来可能”。

最佳答案

你可以在这里使用函数重载:

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

关于typescript - 如何从泛型函数中的参数类型推断返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52302678/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com