TypeScript接口泛型返回类型未被正确检查问题
TypeScript 5.2.2泛型返回类型检查疏漏
截至TypeScript 5.2.2版本,存在一处类型检查漏洞:当类实现接口时,接口定义的泛型返回类型与实际返回的泛型实例类型不匹配,但TypeScript并未检测到该错误。
代码示例
class Foo<T> { constructor(sth: T) {} } interface Test { bar(): Foo<{ a: number }>; } class CTest implements Test { bar() { return new Foo({ b: 1 }); } }
问题说明
接口Test明确要求bar()方法返回Foo<{ a: number }>类型,但实现类CTest的bar()方法返回的是Foo<{ b: 1 }>——两者的泛型参数类型完全不匹配,却未被TypeScript识别为错误。
内容的提问来源于stack exchange,提问作者Minh Nghĩa
相关产品推荐
相关产品推荐

