Typescript WTF Moments 11: Function Unions: any Param Is Not any

tylim88

Acid Coder

Posted on December 24, 2022

Typescript WTF Moments 11: Function Unions: any Param Is Not any

observe the code below

type A = ((v: true) => void) | ((v: false) => void)

const abc: A = (v) => { }
//              ^?
abc(1)
//^?
Enter fullscreen mode Exit fullscreen mode

playground
Image description

notice that the type of the parameter when you declare it, is different from the type of the parameter when you call it

We know that when we union 2 function types

type A<B,C,D,E> = ((v:B)=>C) | ((v:D)=>E)
Enter fullscreen mode Exit fullscreen mode

is equivalent to

type A<B,C,D,E> = (v:B & D)=> (C|E)
Enter fullscreen mode Exit fullscreen mode

so the type of the first code should be

type A = (v: true & false) => void
Enter fullscreen mode Exit fullscreen mode

since true & false is never, the type when we call it is the correct type

so what is happening to the declaration type?

turn out this is because TS fails to infer the type at this point, which is why it returns the any type(TS seem to use any type for problematic situations)

so it is still safe?

It is, because we will know the real type when we try to call it, but it could be misleading and this is the thing you need to keep in mind when using TS

đź’– đź’Ş đź™… đźš©
tylim88
Acid Coder

Posted on December 24, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related