1. 联合类型(Union Types)

语法

type 类型名 = 类型1 | 类型2 | ...

示例

// 定义字符串字面量联合类型(与你代码中的 MessageType 相同)
type MessageType = "success" | "info" | "warning" | "error"; 

// 使用场景:函数参数类型约束
function showNotification(type: MessageType) {
  console.log(type);
}
showNotification("success"); // 正确
showNotification("other"); // 报错:类型 "other" 不在联合类型中

2. 交叉类型(Intersection Types)

语法

type 类型名 = 类型1 & 类型2 & ...

示例

interface Dog {
  bark(): void;
}
interface Animal {
  eat(food: string): void;
}

type DogWithEatingAbility = Dog & Animal;

const myDog: DogWithEatingAbility = {
  bark() { console.log("汪!"); },
  eat(food) { console.log(`正在吃 ${food}`); }
};

3. 元组类型(Tuple Types)

语法

type 类型名 = [类型1, 类型2, ...]

示例

type Coordinates = [number, number]; // 表示[x, y]

const point: Coordinates = [10, 20]; // 正确
const invalidPoint: Coordinates = [10, "20"]; // 报错:第二个元素类型不符

4. 对象类型定义

语法

type 类型名 = { 属性名: 类型; ... };

示例

type User = {
  id: number;
  name: string;
  age?: number; // 可选属性
};

const user: User = {
  id: 1,
  name: "张三",
  age: 30 // 可选,不写也允许
};

5. 函数类型定义

语法

type 类型名 = (参数类型) => 返回值类型;

示例

type AddFunction = (a: number, b: number) => number;

const add: AddFunction = (x, y) => x + y;

6. 自定义类型守卫(Type Guard)

语法

type 类型名 = (参数: any) => 参数是否是该类型;

示例

type Dog = { bark: () => void };

function isDog(animal: any): animal is Dog {
  return "bark" in animal;
}

const testObj = { bark: () => console.log("汪") };
if (isDog(testObj)) {
  testObj.bark(); // 类型已确定为 Dog
}

7. 泛型类型(Generics)

语法

type 类型名<T> = (参数: T) => ...;

示例

type Mapper<T> = (value: T) => T;

const double: Mapper<number> = (num) => num * 2;
const uppercase: Mapper<string> = (str) => str.toUpperCase();

关键注意事项:

  1. 类型别名 vs 接口

    • 类型别名(type)支持联合类型、交叉类型等复杂定义,适合动态场景。
    • 接口(interface)更适合描述对象结构,支持继承和合并。
最后修改:2025 年 04 月 18 日
如果觉得我的文章对你有用,请随意赞赏