TypeScript未对函数传入可选属性报错问题咨询
TypeScript不报错的原因及合理性分析
先明确两个示例的代码
示例1
type A = { b?: string; }; function fn(str: string) { console.log(str.length); } const a: A = {}; fn(a.b); // 无报错
示例2
type B = { c: string; }; type A = { b?: B; }; function fn(str: string) { console.log(str.length); } const a: A = {}; fn(a.b.c); // 无报错
不报错的核心原因:严格空检查未开启
你的TypeScript 4.6.2不报错,本质是**strictNullChecks配置项未启用**(默认值为false,除非手动开启全局严格模式)。
- 对于示例1:
a.b的实际类型是string | undefined,但当strictNullChecks: false时,TypeScript允许undefined隐式赋值给string类型,因此不会触发错误。 - 对于示例2:
a.b的类型是B | undefined,关闭严格空检查后,TypeScript不会校验a.b是否为undefined,直接允许访问其属性c,自然也不会报错。
是否理应报错?
从类型安全和运行时稳定性的角度,这两个场景完全应该报错:
- 示例1运行时会出现
Cannot read property 'length' of undefined错误; - 示例2运行时会直接抛出
Cannot read property 'c' of undefined错误。
只有当你在tsconfig.json中开启严格空检查(或全局严格模式),TypeScript才会给出符合预期的类型错误提示:
{ "compilerOptions": { "strict": true, // 开启全局严格模式,包含strictNullChecks // 或单独开启: // "strictNullChecks": true, "target": "ESNext", "module": "CommonJS" // 其他配置... } }
开启后,示例1会提示“类型'string | undefined'的参数不能赋给类型'string'的参数”;示例2会提示“对象可能为'undefined'”。
内容的提问来源于stack exchange,提问作者Daniel Loiterton
相关产品推荐
相关产品推荐

