Readonly<Type> 可将一个类型中所有属性转换为只读属性。以 User 类型为例:


type User = {

  name: string;

  age: number;

  gender: string;

}

经 Readonly<Type> 转换后得到:


type ReadonlyUser = Readonly<User>;

const readonlyUser: ReadonlyUser = {

  /** `name` 属性是只读的 */

  name: 'Olive',

  /** `age` 属性是只读的 */

  age: 18,

  /** `gender` 属性是只读的 */

  gender: 'female',

}

转换后的 ReadonlyUser 类型与下面的类型是等价的:


type ReadonlyUser = {

  readonly name: string;

  readonly age: number;

  readonly gender: string;

};

Readonly<Type> 是如何转换类型的呢?


/** * Make all properties in T readonly */

type Readonly<T> = {

  readonly [P in keyof T]: T[P];

};
  • 遍历类型 T,将类型 T 中的属性作为 key;
  • 在属性 key 前面加 readonly 修饰符,使其转换为只读属性;
  • 只读属性的值为 T 类型中对应属性的值,即 T[P]。

Playground Link

Last modification:August 15, 2024
If you think my article is useful to you, please feel free to appreciate