为何无法在带扩展运算符的元组上使用flatMap?有无解决办法?
问题原因
这个错误是TypeScript处理带扩展元素的元组类型时的类型推断逻辑导致的:
Groups元组的第一个元素,其blocks是元组类型[{ type: "start" }];而后面扩展的可变元素,blocks是数组类型{ type: "a" | "b"; param?: string }[]。- 调用
flatMap时,TypeScript会尝试推导所有group.blocks的公共兼容类型,但{type: "start"}和{type: "a" | "b"}的type属性无交集,无法自动合并,因此抛出类型不兼容错误。
解决办法
以下是几种可行的修复方案:
方案1:统一blocks的类型为数组
将第一个元素的blocks从元组改为数组类型,让整个元组的元素类型保持一致:
type Groups = [ { id: "start"; blocks: { type: "start" }[] }, ...{ id: string; blocks: { type: "a" | "b"; param?: string }[] }[] ]; const groups: Groups = [ { id: "start", blocks: [{ type: "start" }] }, { id: "yo", blocks: [{ type: "a" }] }, ]; groups.flatMap(group => group.blocks) // 类型校验通过
方案2:显式指定flatMap的泛型参数
直接声明flatMap返回的元素类型为三种type的联合类型,跳过自动推断:
type Groups = [ { id: "start"; blocks: [{ type: "start" }] }, ...{ id: string; blocks: { type: "a" | "b"; param?: string }[] }[] ]; const groups: Groups = [ { id: "start", blocks: [{ type: "start" }] }, { id: "yo", blocks: [{ type: "a" }] }, ]; groups.flatMap<{ type: "start" | "a" | "b"; param?: string }>(group => group.blocks)
方案3:使用类型断言
对group.blocks进行类型断言,强制其兼容联合类型数组:
type Groups = [ { id: "start"; blocks: [{ type: "start" }] }, ...{ id: string; blocks: { type: "a" | "b"; param?: string }[] }[] ]; const groups: Groups = [ { id: "start", blocks: [{ type: "start" }] }, { id: "yo", blocks: [{ type: "a" }] }, ]; groups.flatMap(group => group.blocks as { type: "start" | "a" | "b"; param?: string }[])
内容的提问来源于stack exchange,提问作者Baptiste Arnaud
相关产品推荐
相关产品推荐

