我想知道为什么以下代码在打字稿中接受null:
// 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
似乎与undefined
答案 0 :(得分:1)
您输入了错误的函数。要将foo
键入为() => number
并将其定义为返回null
,您应该这样写:
const foo
: () => number // type def
= () => null; // function def
启用了严格的null检查,此throws an error符合预期。