如何从可空的ParentType中引用User子类型?
TypeScript可空嵌套类型的引用方法
当父类型包含多层可空嵌套(比如ParentType里的viewer和userByUuid都可能为null),直接用链式索引ParentType['viewer']['userByUuid']会触发TypeScript类型错误——因为无法确定ParentType或viewer是否为null。这里提供两种可靠的解决方法:
方法一:用NonNullable过滤空值后索引
先通过NonNullable工具类型排除ParentType的null可能性,再逐层索引内部类型:
type ParentType = { viewer : { userByUuid: { username: string | null; legalName: string | null; } | null; } | null; } // 引用得到目标User类型 type User = NonNullable<ParentType>['viewer']['userByUuid'];
这个方法简洁直接,NonNullable<ParentType>会返回ParentType去掉null后的类型,后续链式索引就能安全访问到userByUuid的完整类型(包括它自身的null可能性)。
方法二:用条件类型推导
通过条件类型的infer关键字,从ParentType中自动推导userByUuid的类型,适配更复杂的嵌套场景:
type ParentType = { viewer : { userByUuid: { username: string | null; legalName: string | null; } | null; } | null; } // 定义通用提取工具类型 type ExtractUser<T> = T extends { viewer: { userByUuid: infer U } } ? U : never; // 引用得到目标User类型 type User = ExtractUser<ParentType>;
条件类型会自动匹配ParentType的非空分支,提取出userByUuid的类型U,最终得到你需要的User类型。
内容的提问来源于stack exchange,提问作者Xiangyu.Wu
相关产品推荐
相关产品推荐

