TypeScript中的Type

半兽人 发表于: 2025-07-28   最后更新时间: 2025-07-28 09:50:41  
{{totalSubscript}} 订阅, 43 游览

在 TypeScript 中,type 是用来定义 类型别名(Type Alias) 的关键字。它的作用是给一个复杂或重复的类型结构起个名字,便于复用和代码更清晰。

一、基本语法

type 类型名 = 类型定义;

二、常见示例

1. 定义简单类型别名

type Age = number;
let myAge: Age = 25;

这相当于:

let myAge: number = 25;

2. 定义对象类型

type Person = {
  name: string;
  age: number;
};

const user: Person = {
  name: "Alice",
  age: 30
};

3. 定义联合类型

type Status = "success" | "error" | "loading";

let currentStatus: Status = "loading";

4. 结合泛型使用

type Response<T> = {
  code: number;
  data: T;
};

const res: Response<string> = {
  code: 200,
  data: "OK"
};

5. 用 type 定义函数类型

type Greet = (name: string) => string;

const greet: Greet = (name) => `Hello, ${name}`;

这是定义了一个函数变量 greet,它的类型是 Greet,函数接收一个 name 参数,返回一个字符串 "Hello, xxx"

三、type vs interface 有什么区别?

特性 type interface
定义基本类型别名
定义对象结构
支持扩展(继承) ✅(用 & ✅(用 extends
支持合并声明 ✅(可以重复定义 interface,会自动合并)

示例对比:

type A = { foo: string };
type B = A & { bar: number };  // 合并A和B

interface A { foo: string }
interface B extends A { bar: number }

总结一句话:

type 是给任何类型(基本类型、对象、联合类型、函数等)起名字的工具,适合表达更灵活或组合型的类型结构,是 TypeScript 中非常强大的工具之一。

更新于 2025-07-28
在线,1小时前登录

查看TypeScript更多相关的文章或提一个关于TypeScript的问题,也可以与我们一起分享文章