程序员求职经验分享与学习资料整理平台

网站首页 > 文章精选 正文

TypeScript 的对象类型、类型别名和类:你能写的,不止是“变量”

balukai 2025-05-14 11:57:18 文章精选 1 ℃

今天我们往更实战、更贴近业务开发的方向走一步 —— 来看三个关键词:

对象类型

类型别名

类型安全的类(Class)

01|对象类型怎么定义?

在 JavaScript 里,我们经常写对象:

const product = {
  name: "Table",
  unitPrice: 450
}

在 TypeScript 中,我们可以为这种对象结构定义“类型”,也就是告诉 TS:

  • 这个对象里有哪些字段
  • 每个字段是什么类型
const product: { name: string; unitPrice: number } = {
  name: "Table",
  unitPrice: 450
}

小技巧:

  • 属性之间可以用 ; 或 , 分隔;
  • TS 通常也能自动推断对象的结构类型,但你手动加上更清晰、更安全

02|想让属性变“可选”?加个问号就搞定!

有时候对象里的字段不是每次都有,比如:

type Product = {
  name: string;
  unitPrice?: number; // 可选字段
}

或者函数参数:

function getPrice(name: string, unitPrice?: number) {
  // unitPrice 不是每次必须传
}

? 表示「这个参数是可传可不传的」,TS 编译器不会报错,但你要记得在使用前判断它是否存在。

03|类型别名:用 type 关键字“起个名字”

如果你觉得对象类型太长,老是重复写不方便,可以用 type 创建一个“别名”:

type Product = {
  name: string;
  unitPrice?: number;
}

之后你就可以直接用 Product 来定义变量、参数类型、返回值等:

const table: Product = { name: "Desk", unitPrice: 999 };

还可以组合类型:

type Info = { createdAt: Date };
type ExtendedProduct = Product & Info;

记住:

  • & 表示交叉类型,合并多个结构;
  • | 表示联合类型,可能是 A 也可能是 B。

04|类(Class)也能加类型,让对象更结构化!

如果你更习惯“面向对象”的风格,TypeScript 支持你用类(Class)定义结构:

class Product {
  name: string;
  unitPrice: number;

  constructor(name: string, unitPrice: number) {
    this.name = name;
    this.unitPrice = unitPrice;
  }

  getDiscountedPrice(discount: number): number {
    return this.unitPrice * (1 - discount);
  }
}

你也可以这样写得更简洁:

class Product {
  constructor(
    public name: string,
    public unitPrice: number
  ) {}

  getDiscountedPrice(discount: number): number {
    return this.unitPrice * (1 - discount);
  }
}

public 修饰参数时,TS 会自动创建属性并赋值!

总结小卡片来了!

概念

用途

备注

{}

对象类型

描述对象结构


?

可选属性

属性或参数非必填


type

别名

给复杂结构起名


&

交叉类型

同时具备多个类型的属性


|

联合类型

可以是多种类型之一

class

面向对象建模


类型注解

保证构造函数、方法参数、返回值类型一致


最近发表
标签列表