TypeScript泛型函数赋值报错:KeyIndexable缺失ObjectA属性如何解决?
问题分析与解决方案
你遇到的错误本质是函数类型的逆变不兼容:
- 左侧的泛型函数类型
<T extends KeyIndexable>(t: T) => void要求这个函数能接收所有符合KeyIndexable约束的类型(比如任意带字符串索引的对象)。 - 右侧的函数
(a: ObjectA) => void只能接收ObjectA类型,无法处理其他KeyIndexable子类型,因此类型不匹配。
根据你的实际需求,有以下几种解决方式:
方式1:让右侧函数兼容泛型约束
如果你确实需要 x 能处理任意 KeyIndexable 类型,把右侧也改成泛型函数:
interface KeyIndexable { [key: string]: any; } interface ObjectA extends KeyIndexable { a: string; b: number; } let x: <T extends KeyIndexable>(t: T) => void; x = <T extends KeyIndexable>(t: T) => console.log('x');
方式2:缩小左侧函数的类型范围
如果 x 只需要处理 ObjectA 类型,直接去掉泛型,指定参数为 ObjectA:
interface KeyIndexable { [key: string]: any; } interface ObjectA extends KeyIndexable { a: string; b: number; } let x: (t: ObjectA) => void; x = (a: ObjectA) => console.log('x');
方式3:调整泛型约束为ObjectA
如果希望 x 能处理 ObjectA 及其子类,把泛型约束改为 ObjectA:
interface KeyIndexable { [key: string]: any; } interface ObjectA extends KeyIndexable { a: string; b: number; } let x: <T extends ObjectA>(t: T) => void; x = (a: ObjectA) => console.log('x');
内容的提问来源于stack exchange,提问作者Antediluvian
相关产品推荐
相关产品推荐

