Variable return types based on string literal type argument

后端 未结 3 813
隐瞒了意图╮
隐瞒了意图╮ 2021-01-01 13:02

Can I have variable return type based on the value of a string literal type argument in TypeScript 1.8 or 2.0?

type Fruit = \"apple\" | \"orange\" 
function          


        
3条回答
  •  醉梦人生
    2021-01-01 14:08

    Yes you can. You just need to test your test variable with instanceof. Typescript will then limit the type.

    type Fruit = "apple" | "orange" 
    function doSomething(foo: Fruit): string | string[] {
        if (foo == "apple") return "hello";
        else return ["hello","world"]
    }
    
    // here the type is still inferred as: string | string[]
    var test = doSomething("orange");
    
    if (test instanceof String) {
        // TypeScript knows test is type: string
        doSomethingWithString(test);
    } else {
        // TypeScript knows test is type: string[]
        doSomethingWithStringArray(test);
    }
    
    function doSomethingWithString(input: string) {}
    function doSomethingWithStringArray(input: string[]) {}
    

    UPDATE

    You may just want to make the method generic instead.

    function doSomething(foo: Fruit): T {
        if (foo == "apple") return "hello";
        else return ["hello","world"]
    }
    
    var test1 = doSomething("apple");
    var test2 = doSomething("orange");
    

    Or another option would be to invert the flow to something like this:

    type Fruit = "apple" | "orange" 
    function doSomething(foo: Fruit): void {
        if (foo == "apple") 
            doSomthingWithString("hello");
        else 
            doSomethingWithStringArray(["hello","world"]);
    }
    
    function doSomethingWithString(input: string) {}
    function doSomethingWithStringArray(input: string[]) {}
    

    UPDATE

    Actually I believe John White's is a much better answer.

提交回复
热议问题