基于字符串文字类型参数的变量返回类型

dan*_*cek 18 typescript

我可以根据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");
Run Code Online (Sandbox Code Playgroud)

错误:TS2322:输入'string | string []'不能赋值为'string []'.

Joh*_*isz 34

是的,您可以使用过载签名来实现您想要的:

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 test1: string[] = doSomething("orange");
let test2: string = doSomething("apple");
Run Code Online (Sandbox Code Playgroud)

在TypeScript Playground上进行现场演示

尝试指派doSomething("apple")test1会产生一个编译时类型错误:

let test1: string[] = doSomething("apple");
 // ^^^^^
 // type string is not assignable to type string[]
Run Code Online (Sandbox Code Playgroud)

重要的是要注意,确定使用哪个重载签名必须始终在函数实现中手动完成,并且函数实现必须支持所有重载签名.

在TypeScript中,每次重载都没有单独的实现,例如C#.因此,我发现在运行时强化TypeScript类型检查是一种很好的做法,例如:

switch (foo) {
    case "apple":
        return "hello";
    case "orange":
        return ["hello", "world"];
    default:
        throw new TypeError("Invalid string value.");
}
Run Code Online (Sandbox Code Playgroud)

  • 我相信这是一个比我接受的答案更好的答案.请将此标记为正确答案. (4认同)