Typescript WTF Moments 11: Function Unions: any Param Is Not any
Acid Coder
Posted on December 24, 2022
observe the code below
type A = ((v: true) => void) | ((v: false) => void)
const abc: A = (v) => { }
// ^?
abc(1)
//^?
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)
is equivalent to
type A<B,C,D,E> = (v:B & D)=> (C|E)
so the type of the first code should be
type A = (v: true & false) => void
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
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
November 28, 2024
November 8, 2024
August 20, 2024