Z
ZHANK
类型系统

类型别名

用 type 关键字定义可复用的类型别名

类型别名

type 关键字让你给任何类型起个名字,大幅提升代码可读性。

学完本章你将: 掌握 type 定义、组合类型别名。


基本类型别名

typescript
// 基础别名
type UserID = string;
type Score = number;

const id: UserID = "usr_123";
const score: Score = 95;

// 联合类型别名
type Status = "active" | "inactive" | "banned";
const userStatus: Status = "active";

// 函数类型别名
type Callback<T> = (data: T) => void;
const onSuccess: Callback<string> = (msg) => console.log(msg);

对象类型别名

typescript
// 对象形状
type Point = {
    x: number;
    y: number;
};

type Circle = {
    center: Point;
    radius: number;
    color?: string;
};

const circle: Circle = {
    center: { x: 0, y: 0 },
    radius: 10,
};

// 嵌套别名
type Address = {
    street: string;
    city: string;
    zip: string;
};

type User = {
    id: number;
    name: string;
    address: Address; // 复用
};

组合与扩展

typescript
// 交叉扩展
type Base = { id: number; createdAt: Date };
type WithName = Base & { name: string };
type WithEmail = WithName & { email: string };

const user: WithEmail = {
    id: 1,
    createdAt: new Date(),
    name: "Alice",
    email: "alice@test.com",
};

// 并集类型
type StringOrNumber = string | number;
type Nullable<T> = T | null;

type MaybeUser = Nullable<WithEmail>;

模板字面量类型

typescript
// 动态字符串类型(TS 4.1+)
type EventName = `on${Capitalize<string>}`;
// "onClick" | "onChange" | ...

type Color = "red" | "green" | "blue";
type Size = "small" | "medium" | "large";
type Variant = `${Size}-${Color}`;
// "small-red" | "small-green" | ... | "large-blue"

type CSSProperty = "margin" | "padding";
type CSSDirection = "top" | "right" | "bottom" | "left";
type CSSKey = `${CSSProperty}-${CSSDirection}`;
// "margin-top" | "margin-right" | ...