Object.values丢失undefined属性,TypeScript类型校验失效如何解决?
TypeScript类型推断问题:Object.values处理可选属性时的类型错误
问题代码
type Foo = { x?: string | undefined } const foo: Foo = { x: undefined } const bar = Object.values(foo).map(x => x.toLowerCase())
这段代码运行时会抛出Cannot read properties of undefined (reading 'toLowerCase')错误,但TypeScript却错误地推断Object.values(foo)的类型为string[],即使显式给x添加| undefined也无法修正这个类型推断偏差,导致潜在bug无法被提前发现。
解决方法
明确属性类型,移除可选符
TypeScript对Object.values的默认类型推断会忽略可选属性中的undefined值,将x的定义从可选属性改为明确的string | undefined类型,就能让TypeScript正确识别数组元素可能为undefined:type Foo = { x: string | undefined; } const foo: Foo = { x: undefined }; // 此时Object.values(foo)会被推断为(string | undefined)[] const bar = Object.values(foo).map(x => x?.toLowerCase());开启严格类型检查模式
在tsconfig.json中开启严格模式相关选项,强制TypeScript对null和undefined进行严格校验:{ "compilerOptions": { "strict": true, // 开启全部严格检查规则 "strictNullChecks": true // 单独开启null/undefined严格校验 } }开启后,TypeScript会更精准地推断类型,及时提示你处理
undefined的情况。自定义工具函数修正
Object.values的类型推断
如果无法修改原类型定义,可以封装一个工具函数来替代原生Object.values,确保返回类型包含所有可能的属性值类型:type ObjectValues<T> = T[keyof T][]; function getObjectValues<T>(obj: T): ObjectValues<T> { return Object.values(obj) as ObjectValues<T>; } // 使用自定义函数替代原生Object.values const bar = getObjectValues(foo).map(x => x?.toLowerCase());
内容的提问来源于stack exchange,提问作者riv
相关产品推荐
相关产品推荐

