为什么元组联合类型的.includes()方法要求入参为never类型?
报错根本原因
TypeScript 对联合类型调用方法时,会自动取所有联合成员对应方法的参数类型的交集,作为最终方法的入参类型。
你代码中的schema每个属性都是as const声明的只读常量数组,不同属性的数组元素类型分别是:
foo属性:readonly ["foo"],includes方法入参类型为"foo"bar属性:readonly ["bar"],includes方法入参类型为"bar"baX属性:readonly ["bar", "baz"],includes方法入参类型为"bar" | "baz"
当你用联合类型keyof typeof schema索引schema得到array时,array的类型是上述三个数组类型的联合,对应的includes方法入参就是三个类型的交集,最终计算结果为never,因此传入任何实际值都会触发类型报错。
合理解决方案
- 方案1:给
schema显式声明类型,统一所有属性的数组元素类型为Word,是最推荐的类型安全方案
type Word = "foo" | "bar" | "baz"; // 显式声明schema类型 const schema: Record<string, readonly Word[]> = { foo: ["foo"] as const, bar: ["bar"] as const, baX: ["bar", "baz"] as const, }; const testFn = (schemaKey: keyof typeof schema, word: Word) => { const array = schema[schemaKey] array.includes(word); // 无报错 }
- 方案2:用泛型约束参数,让TypeScript推导单个键对应的数组类型,避免计算联合类型的交集
const testFn = <T extends keyof typeof schema>(schemaKey: T, word: Word) => { const array = schema[schemaKey] (array as readonly Word[]).includes(word); // 无报错 }
- 方案3:直接将
array断言为readonly Word[],适合确定schema所有属性值都是合法Word数组的场景
const testFn = (schemaKey: keyof typeof schema, word: Word) => { const array = schema[schemaKey] as readonly Word[] array.includes(word); // 无报错 }
直接将参数断言为
never的风险 这种做法不可行,存在严重的类型安全隐患。never是代表不存在的值的类型,将word断言为never本质是完全绕过了TypeScript的类型校验:后续如果schema结构变更、参数传入非法值,TypeScript都不会给出任何错误提示,直接丧失了类型保护能力,不建议使用。
内容的提问来源于stack exchange,提问作者Michal Kurz
相关产品推荐
相关产品推荐

