0

I would like to know why the following code accepts null in typescript:

TS playground

// 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
  • For 1 & 2: 1 || null is known by the compiler to be 1 and so the type is number, not number | null. For 3: you need to turn on the --strictNullChecks compiler option on. Commented Mar 17, 2019 at 20:02

1 Answer 1

1

You mistyped your functions. To type foo as () => number and to define it as returning null, you should write that:

const foo
  : () => number // type def
  = () => null;  // function def

With strict null checks enabled, this throws an error, as expected.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.