查找: 错误 Strict 模式配置
找错误 中等
题目
这个 code 编译不使用 strict 模式但 错误使用 strictNullChecks. 查找 issue:
代码
interface Config {
port: number;
}
const config: Config = JSON.parse("{}");
console.log(config.port);
提示
JSON.parse 返回任何. 什么's actually in parsed 对象?
解释
JSON.parse 返回 任何, 哪个 bypasses 类型检查. 空对象 {} 有否 port 属性, 所以 配置.port 是 undefined at 运行时. 使用 strict 模式, assignment 从 任何 到 配置 是允许但 运行时 behavior 是错误. Fix: 验证 parsed JSON or use 运行时检查: 如果 (typeof 配置.port !== '数字') throw 新错误('无效配置');.
查阅不认识的术语
新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。
解读错误信息
用大白话解释常见错误——什么意思、为什么发生、如何修复。
动手做项目
通过引导式项目应用所学,含起始代码与解决方案。