TypeScript类型报错:已判空仍提示Definition|undefined不可赋值
问题分析与解决方案
你遇到的问题核心是TypeScript对Object.keys()的类型推断限制,而非tsconfig配置错误(不过严格模式会放大这个问题)。
为什么判空后仍报错?
虽然你定义defs为Record<string, Definition>,但TypeScript出于兼容性考虑,会将Object.keys(defs)的返回值类型推断为string[],而非keyof typeof defs。这意味着当你用string类型的type去索引defs时,TS无法确认该type一定是defs的有效键,因此defs[type]的类型会被判定为Definition | undefined——哪怕你做了判空,回调函数的作用域也可能导致TS无法正确收窄类型。
解决方法
方法1:类型断言收窄键类型
将遍历得到的type断言为defs的键类型,让TS明确该键是有效的:
public static addDefinitions(defs: Record<string, Definition>): void { Object.keys(defs).forEach((type: string): void => { const typedKey = type as keyof typeof defs; const def = defs[typedKey]; if (def != undefined) { this.addDefinition(typedKey, def); } }); }
方法2:改用for...in循环
for...in循环能让TS正确推断键的类型,避免string[]带来的类型模糊:
public static addDefinitions(defs: Record<string, Definition>): void { for (const type in defs) { if (defs.hasOwnProperty(type) && defs[type] != undefined) { this.addDefinition(type, defs[type]); } } }
关于tsconfig的说明
如果你的tsconfig.json中开启了strictNullChecks(默认在strict模式下开启),TS会对空值检查更严格,这是正常的类型安全机制,并非配置错误。上述两种方法都能在严格模式下正常工作。
内容的提问来源于stack exchange,提问作者DerHerrGammler
相关产品推荐
相关产品推荐

