共计 1008 个字符,预计需要花费 3 分钟才能阅读完成。
一、Interface 与 type 的区别
1、Interface 可以声明合并,type 不行
声明同名的类型,Interface 同名会合并,而 type 重名会报错
* 注意:如果 interface 合并的时候,同名属性值对应的类型不兼容,则会报错!
例如:
interface P1{name: string;}
interface P1{name: number;}
//throw error!!!
2、类型扩展的方式不同
Interface 基于 extends 继承扩展基类类型,而 type 利用 & 交集 扩展
* 注意:如果定义 type 的交集类型时,同名属性值对应的类型存在冲突,会导致类型变为never!
例如:
3、type 可以被基础类型定义,而 interface 仅可以描述对象结构的类型
interface SomeObjs {// 声明属性和对应类型}
type PrimitiveTypes = number | string
二、探讨为什么 interface 赋值给 Record 需要索引签名
索引签名:对数组或者对象等索引值以及索引返回值进行通用类型定义。其索引值可接受的类型有string、number、symbol。
在利用 type Record 定义一系列属性和对应类型的时候,interface 需要添加索引签名而 type 不用
例如:
interface MyInterface {foo : string;}
type MyType = {foo : string;}
const obj1 : MyInterface = {foo : 'obj1'}
const obj2 : MyType = {foo : 'obj2'}
let record : Record = {}
// 正常编译
record = obj1
// 报错:index signature missing
record = obj2
可以理解为:
Record 限制了属性的类型和值的类型。而 Interface 由于可以声明合并,因此此刻的 MyInterface 并不一定是最终的类型结构,后续的合并可能会存在类型不与 Record 一致的情况。
而 type 则不存在这类隐患!
因此为和 Record 匹配,MyInterface 应添加索引签名,对属性和值的类型进行检查,写为:
interface MyInterface {
foo : string;
[key : string] : string;
}
原文地址: 【Typescript】Interface 和 type 的区别;探讨为什么 interface 赋值给 Record 需要索引签名