定义方式
- 接口(interface):使用
interface
关键字定义。接口定义以名称开始,后面跟着花括号包裹的成员定义。例如:
interface Person {
name: string;
age: number;
}
- 类型别名(type alias):使用
type
关键字定义。类型别名可以定义基本类型、联合类型、交叉类型等。例如:
type PersonType = {
name: string;
age: number;
};
功能特性
- 接口(interface):
- 可声明合并,即多个同名接口声明会自动合并为一个接口。例如:
interface User {
name: string;
}
interface User {
age: number;
}
// 此时User接口有name和age属性
let user: User = {name: 'John', age: 30};
- 主要用于定义对象形状,只能描述对象类型结构,对其他类型支持有限。
- 类型别名(type alias):
- 不能声明合并。
- 功能更灵活,除了定义对象类型,还能定义基本类型别名(如
type StringAlias = string;
)、联合类型(如 type ID = string | number;
)、交叉类型(如 type Admin = User & { isAdmin: boolean };
)等。
使用场景
- 接口(interface):
- 当主要描述对象的结构,且希望支持声明合并时,优先使用接口。例如在定义 React 组件的 props 类型时,接口很常用。
interface ButtonProps {
text: string;
onClick: () => void;
}
const Button = ({text, onClick}: ButtonProps) => (
<button onClick={onClick}>{text}</button>
);
- 类型别名(type alias):
- 当需要定义联合类型、交叉类型或基本类型别名,或者不需要声明合并功能时,使用类型别名。例如定义函数参数可能的不同类型:
type Callback = () => void;
type EventHandler = (event: any) => void;
type Handler = Callback | EventHandler;
function handle(handler: Handler) {
// 处理逻辑
}