TypeScript条件类型判断undefined不符合预期的问题
TypeScript条件类型处理联合类型的问题解析
问题原因
你遇到的是TypeScript分布式条件类型的特性:当条件类型的泛型参数是联合类型时,TypeScript会自动将联合类型的每个成员单独代入条件进行判断,再把结果合并成新的联合类型。
对应你的代码:
type stringUndefined = "string" | undefined; type What<T> = T extends undefined ? "true" : "false";
What<stringUndefined>会被拆解为What<"string"> | What<undefined>,最终得到"false" | "true",这就是结果不符合预期的核心原因。
解决方案
根据实际需求,有两种针对性的处理方式:
1. 判断类型是否严格等于undefined
如果要让整个联合类型作为一个整体参与条件判断,而非拆分成员,只需将泛型参数用方括号包裹,规避分布式处理:
type stringUndefined = "string" | undefined; type What<T> = [T] extends [undefined] ? "true" : "false"; // 此时What<stringUndefined>的类型为"false",因为整个类型并非严格等于undefined const result: What<stringUndefined> = "false";
2. 判断联合类型中是否包含undefined
如果你的真实需求是检测联合类型内是否存在undefined成员,应将条件逻辑反转:
type stringUndefined = "string" | undefined; type ContainsUndefined<T> = undefined extends T ? "true" : "false"; // 此时ContainsUndefined<stringUndefined>的类型为"true" const result: ContainsUndefined<stringUndefined> = "true";
内容的提问来源于stack exchange,提问作者Twiggeh
相关产品推荐
相关产品推荐

