1. 寫法上
type
使用關鍵字 type 進行聲明。
interface
使用關鍵字 interface 進行聲明。
// 使用 type
type MyType = {param: string;
};// 使用 interface
interface MyInterface {param: string;
}
2. 可合并性
interface
具有可合并性,允許在同一作用域內多次聲明同名的接口,這些聲明將會合并為一個接口。
type
不具有可合并性,如果多次聲明同名的類型,會報錯。
// interface 具有可合并性
interface MyInterface {param: string;
}interface MyInterface {additionParam: number;
}// 最終合并后的接口
// { param: string; additionParam: number; }
3. 拓展性
interface
支持接口的擴展(extends
關鍵字)。
type
支持聯合類型和交叉類型,但不能使用 extends關鍵字 進行擴展。
// 使用 interface 擴展
interface ExtendedInterface extends MyInterface {newParam: string;
}// 使用 type 交叉類型
type ExtendedType = MyType & { newParam: string};
ts類型操作符& 和 | 的區別
4. 接口的實現
class
可以用implements
實現一個接口。
type 不能被類實現。
// 使用 interface 實現
interface MyInterface {prop: string;
}class MyClass implements MyInterface {prop = "value";
}
5. 使用場景
一般來說,interface
更適合聲明一個對象。
interface Person {name: string;age: number;greet(): void;
}const person: Person = {name: 'John',age: 30,greet() {console.log('Hello!');}
};
type
更適合表示聯合類型、交叉類型和其他高級類型,創建類型別名。
type Status = 'success' | 'error';type Coordinate = {x: number;y: number;
};type Point3D = Coordinate & { z: number };type FunctionType<T> = (arg: T) => void;