在 TypeScript 1.8 或 2.0 中,我可以根据字符串文字类型参数的值获得可变返回类型吗?
type Fruit = "apple" | "orange"
function doSomething(foo : Fruit) : string | string[] {
if (foo == "apple") return "hello";
else return ["hello","world"];
}
var test : string[] = doSomething("orange");
Error: TS2322: Type 'string | string[]' is not assignable to type 'string[]'.
最佳答案
是的,您可以使用重载签名来实现您想要的:
type Fruit = "apple" | "orange"
function doSomething(foo: "apple"): string;
function doSomething(foo: "orange"): string[];
function doSomething(foo: Fruit): string | string[]
{
if (foo == "apple") return "hello";
else return ["hello", "world"];
}
let orange: string[] = doSomething("orange");
let apple: string = doSomething("apple");
尝试将 doSomething("apple")
分配给 orange
会产生编译时类型错误:
let orange: string[] = doSomething("apple");
// ^^^^^^
// type 'string' is not assignable to type 'string[]'
Live demo on TypeScript Playground
重要的是要注意,必须始终在函数实现中手动确定使用了哪个重载签名,并且函数实现必须 support all overload signatures .
TypeScript 中的每个重载都没有单独的实现,例如 C#。因此,我发现在运行时加强 TypeScript 类型检查是一种很好的做法,例如:
switch (foo) {
case "apple":
return "hello";
case "orange":
return ["hello", "world"];
default:
throw new TypeError("Invalid string value.");
}
关于typescript - 基于字符串文字类型参数的变量返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39700093/