TypeScript Utility Types - Readonly: TypeScript 实用类型 - Readonly
Readonly<Type>
可将一个类型中所有属性转换为只读属性。以 User
类型为例:
1 | type User = { |
经 Readonly<Type>
转换后得到:
1 | type ReadonlyUser = Readonly<User>; |
转换后的 ReadonlyUser
类型与下面的类型是等价的:
1 | type ReadonlyUser = { |
Readonly<Type>
是如何转换类型的呢?
1 | /** * Make all properties in T readonly */ |
- 遍历类型
T
,将类型T
中的属性作为 key; - 在属性 key 前面加
readonly
修饰符,使其转换为只读属性; - 只读属性的值为
T
类型中对应属性的值,即T[P]
。