I would like to know why the following code accepts null in typescript:
// Not sure why null is accepted here when I've specified number as the type
const foo = (): number => 1 || null
// Even when enforcing non-nullable
const foo2 = (): NonNullable<number> => 1 || null
// Here tough, it works: null is not a number
const foo3 = (i: number): number => i || null
Seems to be the same with undefined
1 || nullis known by the compiler to be1and so the type isnumber, notnumber | null. For 3: you need to turn on the--strictNullCheckscompiler option on.