如何从含可选属性的TypeScript嵌套类型中提取指定子类型?
从嵌套可选属性的TypeScript类型中提取子类型
已知TypeScript类型Something,其中a和foo均为可选属性:
type Something = { a?: { foo?: { bar: { c: { id: string, countryCode: number, animal: { /* 具体类型定义 */ } } } } } }
需要创建类型MyType,使其等价于Something中嵌套的bar类型,即:
type MyType = { c: { id: string, countryCode: number, animal: { /* 具体类型定义 */ } } }
解决方案
可以通过索引访问类型结合NonNullable工具类型提取目标子类型,具体实现如下:
type MyType = NonNullable<NonNullable<Something['a']>['foo']>['bar'];
代码说明:
Something['a']:获取a属性的类型,结果为{ foo?: { bar: ... } } | undefinedNonNullable<Something['a']>:排除undefined,得到{ foo?: { bar: ... } }NonNullable<...>['foo']:获取foo属性的类型,结果为{ bar: ... } | undefined- 再次使用
NonNullable排除undefined后,通过['bar']即可拿到最终的bar类型
如果你的TypeScript版本在4.9及以上,还可以使用更简洁的可选链风格索引访问:
type MyType = NonNullable<Something['a']?.['foo']?.['bar']>;
内容的提问来源于stack exchange,提问作者I am X
相关产品推荐
相关产品推荐

