Narrowing types in TS, a quick tour

· typescript  · 1 min read

TypeScript type narrowing

Narrowing types in TS, a quick tour

If you’re not comfortable with “type narrowing”, replace it by “type guessing”.

At runtime, TS is sometimes unable to guess what type your variable is about.

Of course, for let a: string = "foo", TS is able to guess (better, it is certain) that a can only be a String.

But what if let a: string | number | null = null ?

Well, when not null, a could be string or number. This cannot be detected at runtime.

function spent(amount: number | string): string {
    return `You spent ${amount.toLowerCase}`
}

This won’t work.

image of error

TS is unable to “guess” if “amount” is “string” or “number”. Well, toLowerCase will work on string, but not with number.

But, a simple “if” solves it :

function spent(amount: number | string): string {
    let res = ""
    if (typeof amount === "string") {
        res = `You spent ${amount.toLowerCase}`
    } else if (typeof amount === "number") {
        res = `You spent ${amount.toString}`
    }
    return res
}

You can copy/paste the above in the TypeScript playground : no error are shown.

How great! TS is able to guess type at runtime.

So, again, if you are lost with “type narrowing”, replace by “type guessing at runtime”.

Best,

David.

Share:
Back to Blog

Related Posts

View All Posts »