Hi FE !
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub

Record

以 typeof 格式快速创建一个类型,此类型包含一组指定的属性且都是必填。

type Coord = Record<'x' | 'y', number>;
// 等同于
type Coord = {
	x: number;
	y: number;
}

具体的复杂业务场景中,一般会接口 Pick 、Partial 等组合使用,从而过滤和重组出新的类型定义。

Partial

将类型定义的所有属性都修改为可选。

type Coord = Partial<Record<'x' | 'y', number>>;

// 等同于
type Coord = {
	x?: number;
	y?: number;
}

Readonly

不管是从字面意思,还是定义上都很好理解:将所有属性定义为自读。

type Coord = Readonly<Record<'x' | 'y', number>>;

// 等同于
type Coord = {
    readonly x: number;
    readonly y: number;
}

// 如果进行了修改,则会报错:
const c: Coord = { x: 1, y: 1 };
c.x = 2; // Error: Cannot assign to 'x' because it is a read-only property.

Pick

从类型定义的属性中,选取指定一组属性,返回一个新的类型定义。

type Coord = Record<'x' | 'y', number>;
type CoordX = Pick<Coord, 'x'>;

// 等用于
type CoordX = {
	x: number;
}

Edit this page
最近更新: 2025/12/2 01:46
Contributors: qdleader
qdleader
本站总访问量 129823次 | 本站访客数 12人