interface 和 type 到底有什么区别?
-
type 可以,interface 不行
1.声明基本类型别名,联合类型,元组等类型。type Name = string // 基本类型 type arrItem = number | string // 联合类型 const arr: arrItem[] = [1,'2', 3] type Person = { name: Name } type Student = Person & { grade: number } // 交叉类型 type Teacher = Person & { major: string } type StudentAndTeacherList = [Student, Teacher] // 元组类型 const list:StudentAndTeacherList = [ { name: 'lin', grade: 100 }, { name: 'liu', major: 'Chinese' } ]
2.使用 typeof 获取实例的 类型进行赋值。
// 当你想获取一个变量的类型时,使用 typeof let div = document.createElement('div'); type B = typeof div
interface 可以,type 不行
interface 能够声明合并。interface Person { name: string } interface Person { // 重复声明 interface,就合并了 age: number } const person: Person = { name: 'lin', age: 18 }
interface 和 type 被typescript设计出来,是完全不同的东西,有各自的职责。interface 是接口,用于描述一个对象。type 是类型别名,用于给各种类型定义别名,让 TS 写起来更简洁、清晰。
-
interface 和 type 到底有什么区别?
作者:rottenpen