Home > Blockchain >  2 return flows in TS and only one is found in autocompletion
2 return flows in TS and only one is found in autocompletion

Time:10-19

I don't figure out why TS can't infer the types of the 2 flows in this example :

function toto(mode: boolean) {
    if (mode) {
        return [42]
    } else {
        return "mike"
    }
}

const test = toto(true) // const test: number[] | "mike"
const test2 = toto(false) // const test2: number[] | "mike"

Test it in the playground.

Why the auto completion puts only the array methods and not the string ones (like toUpperCase) ?

CodePudding user response:

A function return type can only be of one type, so Typescript is merging both flows,.. number[] | 'mike' In a lot of cases this is what you might want.

But you can do function overloads, this will then mean you can have different return types for different inputs.

eg..

function toto(mode: true):number[];
function toto(mode: false):'mike';
function toto(mode: boolean) {
    if (mode === true) {
        return [42]
    } else  {
        return "mike"
    } 
}

const test = toto(true)
const test2 = toto(false)

Be aware that in Typscript literal string types are narrowed, so 'const a = 'hello' is not of type string, it's of type 'hello'. So if you want mike to be of type string you could do this->


function toto(mode: true):number[];
function toto(mode: false):string;
function toto(mode: boolean) {
    if (mode === true) {
        return [42]
    } else  {
        return "mike" as string
    } 
}

const test = toto(true)
const test2 = toto(false)
  • Related