TS入门:type 与 interface
2024年7月25日
在 TypeScript
中,type
是一种定义自定义类型的工具。它允许你为一组类型赋予一个名字,然后在代码中复用这个名字。与 interface
类似,type
可以用于定义对象类型,但它的用途更加广泛。
type
的用途
- 定义基本类型的别名:
ts
type ID = number | string;
let userId: ID = 123; // 合法
userId = "ABC"; // 也合法
- 定义对象类型:
ts
type User = {
id: number;
name: string;
};
let user: User = {
id: 1,
name: "Alice"
};
- 定义联合类型:
ts
type Shape = Circle | Square;
type Circle = {
kind: "circle";
radius: number;
};
type Square = {
kind: "square";
sideLength: number;
};
let shape: Shape = { kind: "circle", radius: 5 };
- 定义交叉类型:
ts
type Name = {
firstName: string;
lastName: string;
};
type Contact = {
email: string;
phone: string;
};
type Person = Name & Contact;
let person: Person = {
firstName: "John",
lastName: "Doe",
email: "john.doe@example.com",
phone: "123-456-7890"
};
- 定义元组类型:
ts
type Point = [number, number];
let point: Point = [1, 2];
与 interface
的区别
虽然 type
和 interface
有相似的功能,但它们也有一些区别:
- 扩展方式:
interface
可以使用extends
进行扩展:
ts
interface Animal {
name: string;
}
interface Dog extends Animal {
breed: string;
}
type
可以使用交叉类型进行扩展:
ts
type Animal = {
name: string;
};
type Dog = Animal & {
breed: string;
};
- 声明合并:
interface
可以多次声明,并自动合并:
ts
interface User {
id: number;
}
interface User {
name: string;
}
let user: User = { id: 1, name: "Alice" };
type
不能多次声明同名类型。
- 复杂类型:
type
可以用于定义更复杂的类型,如联合类型和交叉类型,而interface
不能直接定义这些类型。
示例代码
以下是一些使用 type
的示例代码:
ts
// 基本类型别名
type StringOrNumber = string | number;
let value: StringOrNumber;
value = "hello"; // 合法
value = 42; // 也合法
// 对象类型
type User = {
id: number;
name: string;
};
let user: User = {
id: 1,
name: "Alice"
};
// 联合类型
type SuccessResponse = {
status: "success";
data: any;
};
type ErrorResponse = {
status: "error";
message: string;
};
type APIResponse = SuccessResponse | ErrorResponse;
let response: APIResponse = {
status: "success",
data: { id: 1, name: "Alice" }
};
// 交叉类型
type Person = {
name: string;
};
type Employee = Person & {
employeeId: number;
};
let employee: Employee = {
name: "Bob",
employeeId: 123
};
// 元组类型
type Point = [number, number];
let point: Point = [10, 20];
通过 type
,TypeScript
提供了灵活且强大的方式来定义和使用类型,从而提高代码的可读性和可维护性。
转载说明
本文允许全文转载,转载请注明来源: 平凡公子 - TS入门:type 与 interface