1 个回答

这段代码不管是否打开 strictNullChecks 开头,在最新(4.4版本)的 Playground 中都会报错:

如果开了 strictNullChecks,会报

Function lacks ending return statement and return type does not include 'undefined'.

就是说,缺少返回语句(default)的情况,而且返回类型不含 undeinfed,因为没有显式的 return 实际会返回 undefined

如果关于 strictNullChecks,会报

Not all code paths return a value.

说白了,还是缺少对 default 的处理。再把 noImplicitReturns 关掉可以编译通过。

当然现代 TypeScript 都最好把这两个开关打开,避免不必要的空错误。


以下是参考:

strictNullChecks

By default, values like null and undefined are assignable to any other type. This can make writing some code easier, but forgetting to handle null and undefined is the cause of countless bugs in the world - some consider it a billion dollar mistake! The strictNullChecks flag makes handling null and undefined more explicit, and spares us from worrying about whether we forgot to handle null and undefined.

from: TypeScript: Documentation - The Basics (typescriptlang.org)

另参考:TypeScript: Documentation - Everyday Types (typescriptlang.org)

推荐问题