TypeScript接口泛型推断异常:componentProps类型为何不符合预期?
问题原因及解决办法
核心原因
你定义的MyInterface泛型参数T设置了默认值any,当你使用const foo: MyInterface时没有显式指定泛型参数,TypeScript会自动将T设为any。而InstanceType<any>的结果是any类型,这意味着componentProps会被当作any处理——TypeScript不会对any类型的对象做额外属性校验,所以bar: 'baz'能通过编译。
解决方法
方法1:显式指定泛型参数
直接在MyInterface后指定泛型为typeof TestClass,让TypeScript明确T的类型,从而正确推导componentProps的类型:
const foo: MyInterface<typeof TestClass> = { component: TestClass, componentProps: { bar: 'baz' // 此处会触发编译错误,符合预期 } }
方法2:通过辅助函数自动推导泛型
如果不想每次都手动指定泛型,可以写一个辅助函数,让TypeScript根据传入的参数自动推导T的类型:
function createMyInterface<T extends new abstract (...args: any) => any>(obj: MyInterface<T>) { return obj; } const foo = createMyInterface({ component: TestClass, componentProps: { bar: 'baz' // 此处会触发编译错误 } });
内容的提问来源于stack exchange,提问作者Jan
相关产品推荐
相关产品推荐

