在 React + TypeScript 中,interface 和 type 都可以用来定义类型。它们有很多相同的功能,但也有一些重要区别。
先说结论:定义 React 组件的 Props 时,两者通常都可以使用,没有绝对的优劣之分。
1. 基本定义方式
两者都可以定义对象结构。
使用 interface:
interface Props {
name: string;
age: number;
active: boolean;
}
使用 type:
type Props = {
name: string;
age: number;
active: boolean;
};
可以看到,定义对象类型时,两者几乎一样。
在 React 中都可以这样使用:
interface Props {
title: string;
content: string;
}
function Card({ title, content }: Props) {
return (
<div>
<h2>{title}</h2>
<p>{content}</p>
</div>
);
}
如果换成 type,写法也完全一样。
2. 最大区别:interface 可以重复声明合并
这是两者一个很重要的区别。
interface:允许重复声明,自动合并。
interface User {
name: string;
}
interface User {
age: number;
}
TypeScript 会把它们合并,相当于:
interface User {
name: string;
age: number;
}
使用:
const user: User = {
name: "Tom",
age: 20
};
type:不允许重复定义同名类型。
type User = {
name: string;
};
type User = {
age: number;
};
这样会报错,因为 User 已经定义过了。
3. type 可以定义更多类型
这是 type 一个比较明显的优势。
例如,定义联合类型:
type Status = "success" | "error" | "loading";
定义基本类型别名:
type ID = string | number;
定义元组:
type Point = [number, number];
定义函数类型:
type Callback = (value: string) => void;
这些都可以使用 type,但不能直接用 interface 这样定义。
4. 两者都支持继承或扩展
interface 使用 extends:
interface Person {
name: string;
}
interface Employee extends Person {
salary: number;
}
Employee 就拥有:
type 使用交叉类型 &:
type Person = {
name: string;
};
type Employee = Person & {
salary: number;
};
最终得到的结构也是一样的。
5. React 中的实际应用
例如,你定义一个按钮组件:
interface ButtonProps {
title: string;
disabled?: boolean;
onClick: () => void;
}
function MyButton({
title,
disabled,
onClick
}: ButtonProps) {
return (
<button disabled={disabled} onClick={onClick}>
{title}
</button>
);
}
如果使用 type:
type ButtonProps = {
title: string;
disabled?: boolean;
onClick: () => void;
};
组件本身不需要做任何修改。
6. 总结对比
| 比较项目 | interface | type |
|---|
| 定义对象类型 | 支持 | 支持 |
| 定义 Props | 支持 | 支持 |
| 定义泛型 | 支持 | 支持 |
| extends 继承 | 支持 | 不支持(但可用 &) |
联合类型 \| | 不支持直接定义 | 支持 |
交叉类型 & | 不支持直接定义 | 支持 |
| 重复声明 | 自动合并 | 不允许 |
| 基本类型别名 | 不支持 | 支持 |
7. 建议
在 React + TypeScript 项目中,可以按照下面的习惯使用:
interface:主要用于定义对象结构,例如组件 Props、用户信息、数据模型。type:主要用于联合类型、交叉类型、函数类型、复杂类型组合。
当然,这只是编码习惯,并不是强制规定。
一个核心区别:
interface 更专注于描述对象结构;type 的用途更加广泛,可以给各种类型起别名,也可以组合类型。
两者都能使用泛型。