interface、type 和 abstract class 都能描述结构,但用途并不完全一样。
interface
interface 常用于描述对象形状,尤其适合公共 API 和类实现。
interface User {
id: string;
name: string;
}
class Admin implements User {
constructor(
public id: string,
public name: string,
) {}
}interface 可以重复声明并自动合并,这在扩展第三方类型时有用。
type
type 更灵活,可以表达联合类型、交叉类型和复杂组合。
type Status = "idle" | "loading" | "success" | "error";
type UserWithRole = User & { role: string };如果你要描述的是状态集合、函数类型或复杂类型组合,type 往往更合适。
abstract class
抽象类既可以定义类型,也可以包含共享实现。
abstract class Repository<T> {
abstract findById(id: string): Promise<T | null>;
logQuery(id: string) {
console.log(`find ${id}`);
}
}如果需要子类共享代码,抽象类比 interface 更合适。
泛型
泛型让类型可以被参数化。
function identity<T>(value: T): T {
return value;
}
const name = identity<string>("Alice");泛型常用于集合、API 返回值和工具函数。
interface ApiResponse<T> {
data: T;
error?: string;
}
type UserResponse = ApiResponse<User>;简单选择规则
- 描述对象结构:优先
interface - 描述联合、交叉、工具类型:优先
type - 需要共享实现和继承约束:用
abstract class - 需要类型复用:使用泛型