欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

探索 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

ValueOfkeyof相对应。取出指定类型的所有 value

type ValueOf<T> = T[keyof T]

4.Mutable

用来将所有属性的readonly移除:

type Mutable<T> = {
  -readonly [P in keyof T]: T[P]
}