如何动态解析属性类型混合的嵌套对象?
解决TypeScript嵌套对象解析的类型错误问题
问题原因
TypeScript无法在for...in循环中通过typeof判断自动收窄联合类型的成员。因为attribute是keyof Test(即"stringProperty" | "objectProperty"),循环中TypeScript无法追踪当前attribute具体指向哪个键,所以data[attribute]的类型始终是string | { numberProperty: number },即便你通过typeof排除了字符串类型,TypeScript也无法确认剩余值的具体类型。
可行解决方案
方案1:自定义类型守卫(最安全)
编写类型守卫函数明确判断值的类型,让TypeScript能够正确收窄类型:
interface Test { stringProperty: string objectProperty: { numberProperty: number } } var data: Test = { stringProperty: "someString", objectProperty: { numberProperty: 13 } } // 自定义类型守卫函数 function isNumberPropertyObject(obj: unknown): obj is { numberProperty: number } { return typeof obj === 'object' && obj !== null && 'numberProperty' in obj; } for (const attribute in data) { const value = data[attribute]; if (isNumberPropertyObject(value)) { value.numberProperty = 3; } }
方案2:直接判断属性名(最直观)
由于Test接口的属性是明确的,可以直接判断当前属性是否为目标对象属性:
interface Test { stringProperty: string objectProperty: { numberProperty: number } } var data: Test = { stringProperty: "someString", objectProperty: { numberProperty: 13 } } for (const attribute in data) { if (attribute === 'objectProperty') { data[attribute].numberProperty = 3; } }
方案3:类型断言(快速解决,需确保逻辑正确)
如果能确定排除字符串后剩余值一定是目标对象类型,可以使用类型断言:
interface Test { stringProperty: string objectProperty: { numberProperty: number } } var data: Test = { stringProperty: "someString", objectProperty: { numberProperty: 13 } } for (const attribute in data) { const value = data[attribute]; if (typeof value !== 'string') { (value as { numberProperty: number }).numberProperty = 3; } }
内容的提问来源于stack exchange,提问作者TheWilley
相关产品推荐
相关产品推荐

