TypeScript中如何引用接口可选嵌套属性作为变量类型?
TypeScript中获取可选属性的子属性类型解决方案
问题原因
你定义的foo接口中,bar是可选属性(带?标记),因此foo['bar']的类型是{ baz: { property: string; } } | undefined。当直接尝试访问foo['bar']['baz']['property']时,TypeScript会报错,因为undefined类型上不存在baz属性。
解决方法
方法1:用NonNullable排除undefined类型
如果业务逻辑中确定bar属性一定存在,可以使用TypeScript内置的NonNullable工具类型,先排除foo['bar']中的undefined类型,再访问子属性:
interface foo { bar?: { baz: { property: string; }; }; } // 排除undefined后获取property的类型 type PropertyType = NonNullable<foo['bar']>['baz']['property']; // 类型为string // 使用该类型定义函数参数 function handleProperty(arg: PropertyType) { console.log(arg); } handleProperty('test'); // 正常运行 handleProperty(123); // 类型错误,符合预期
方法2:使用类型可选链(TypeScript 3.7+)
如果允许bar属性不存在,希望参数类型为string | undefined,可以使用类型层面的可选链操作符?,和JavaScript的可选链逻辑一致:
interface foo { bar?: { baz: { property: string; }; }; } // 类型可选链自动处理undefined情况 type PropertyType = foo['bar']?['baz']['property']; // 类型为string | undefined function handleProperty(arg: PropertyType) { console.log(arg); } handleProperty('test'); // 正常运行 handleProperty(undefined); // 正常运行 handleProperty(123); // 类型错误,符合预期
方法3:抽离嵌套类型(推荐复杂场景)
如果接口嵌套层次较深,建议提前抽离嵌套的子类型,既提升代码可读性,也避免类型查询时的可选属性问题:
// 抽离最内层的属性类型 interface Baz { property: string; } // 抽离bar的类型 interface Bar { baz: Baz; } // 定义顶层接口 interface Foo { bar?: Bar; } // 直接使用抽离后的类型 type PropertyType = Baz['property']; // 类型为string function handleProperty(arg: PropertyType) { console.log(arg); }
内容的提问来源于stack exchange,提问作者Rocky
相关产品推荐
相关产品推荐

