为何同类型定义下interface编译报错而type却正常?
TypeScript interface与type的索引兼容性差异
这本质是TypeScript对
interface和type的结构兼容性检查逻辑不同导致的:- 用
type定义的对象类型,TypeScript会直接做结构匹配:只要TTest的所有属性值都符合目标类型{ [index: string]: boolean }的约束,就允许赋值。 - 而
interface定义的类型,TypeScript会将其视为“带有固定属性集合的接口”。当你把它赋值给带索引签名的类型时,TypeScript会额外校验该接口是否显式声明了对应的索引签名。因为ITest只定义了a: boolean,没有声明[index: string]: boolean,TypeScript会顾虑后续可能有人扩展这个接口,添加不符合索引签名约束的属性(比如新增b: string),因此拒绝赋值操作。
- 用
要让
interface的代码通过编译,有两种可行方案:- 给接口添加显式的索引签名:
interface ITest { [index: string]: boolean; a: boolean; } const Itest: ITest = { a: true }; const test: { [index: string]: boolean } = Itest; - 使用类型断言跳过兼容性检查:
const test: { [index: string]: boolean } = Itest as { [index: string]: boolean };
- 给接口添加显式的索引签名:
内容的提问来源于stack exchange,提问作者饕餮饗食
相关产品推荐
相关产品推荐

