为何TypeScript的extends条件类型仅返回其中一个分支?
问题原因及解决方法
核心问题
你写的type Value = typeof multiple extends true ? string[] : string里,typeof multiple得到的是静态类型boolean,而非运行时的具体值true或false。TypeScript会判断「boolean类型是否继承自true类型」——显然boolean是true | false的联合类型,并不完全等于true,因此条件分支走了false的结果,Value最终被推断为string,这就导致给foo赋值['string']时出现类型不匹配的错误。
解决方法
要让TypeScript跟踪multiple的具体类型分支,需要把函数改成泛型函数,将multiple作为泛型参数传入:
const func = <T extends boolean>(multiple: T) => { type Value = T extends true ? string[] : string if (multiple) { const foo: Value = ['string'] // 类型匹配,无错误 } else { const bar: Value = 'string' // 类型匹配,无错误 } }
这样当你传入true作为参数时,泛型T会被推断为true,Value就会是string[];传入false时,T为false,Value为string,完全符合你的预期。
内容的提问来源于stack exchange,提问作者Camilo
相关产品推荐
相关产品推荐

