都可以描述一个对象或者函数
(1). 类型区别:
①. interface只能表示function、object、class类型:
interface A {
name: string;
add: () => void;
}
interface B{
(): void
}
②. type可以表示所有类型:
type C = () => number; // 函数
type D = string; // 字符串
type E = { name: string, age: number } // 对象
(2). 名称:
①. interface可以合并同名接口:
interface A{ name: string }
interface A{ age: number }
②. type不可以:
var x:A = { name: 'xx', age: 20 }
(3). 继承:
①. interface可以继承interface、继承type(使用extends关键字):
②. type也可继承type,也可继承interface(使用&)
③. 举例:
interface A { name: string }
type C = { sex: string }
interface B extends A { age: number } // interface继承interface
interface D extends C { name: string } // interface继承type
type E = { name: string }&C // type继承type
type F = { age: number }&A // type继承interface
(4). 实现:
①. 类可以实现接口,也可以实现type:
②. 举例:
interface A {
name: string;
add: () => void
}
type B = {
age: number,
add: () => void
}
class C implements A {
name: 'xx'
add() { console.log('类实现接口') }
}
class D implements B {
age: 20
add() { console.log('类实现type') }
}
一般,优先用interface来实现,实现不了再用type.