探索 TypeScript 内置工具中的泛型 - 之二:自定义非内置类型示解
最编程
2024-07-27 20:56:09
...
下面是一些较为实用的非TS内置的类型定义
1.DeepReadonly
DeepReadonly
用来深度遍历 T,并将其所有属性变成只读类型
type DeepReadonly<T> = { readonly [P in keyof T]: DeepReadonly<T[P]> }
参考示例如下,约束变量的深层属性为只读:
type DeepReadonly<T> = {
readonly [P in keyof T]: DeepReadonly<T[P]>;
};
interface A {
B: { C: number; };
D: { E: number; }[];
}
const myDeepReadonlyObject: DeepReadonly<A> = {
B: { C: 1 },
D: [ { E: 2 } ],
}
myDeepReadonlyObject.B = { C: 2 }; // error :)
myDeepReadonlyObject.B.C = 2; // error :)
2.ConvertNumberToString
ConvertNumberToString
用来将number
转换为string
类型
type ConvertNumberToString<T> = {
[K in keyof T]: T[K] extends string ? string : T[K]
}
3.ValueOf
ValueOf
与keyof
相对应。取出指定类型的所有 value
type ValueOf<T> = T[keyof T]
4.Mutable
用来将所有属性的readonly
移除:
type Mutable<T> = {
-readonly [P in keyof T]: T[P]
}