utils.d.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /** 提取Promise返回值 */
  2. type UnboxPromise<T extends Promise<any>> = T extends Promise<infer U> ? U : never;
  3. /** 将联合类型转为交叉类型 */
  4. declare type UnionToIntersection<U> = (U extends any ? (k: U) => void : never) extends (
  5. k: infer I,
  6. ) => void
  7. ? I
  8. : never;
  9. /** eg: type result = StringToUnion<'abc'> 结果:'a'|'b'|'c'*/
  10. type StringToUnion<S extends string> = S extends `${infer S1}${infer S2}`
  11. ? S1 | StringToUnion<S2>
  12. : never;
  13. /** 字符串替换,类似js的字符串replace方法 */
  14. type Replace<
  15. Str extends string,
  16. From extends string,
  17. To extends string,
  18. > = Str extends `${infer Left}${From}${infer Right}` ? `${Left}${To}${Right}` : Str;
  19. /** 字符串替换,类似js的字符串replaceAll方法 */
  20. type ReplaceAll<
  21. Str extends string,
  22. From extends string,
  23. To extends string,
  24. > = Str extends `${infer Left}${From}${infer Right}`
  25. ? Replace<Replace<`${Left}${To}${Right}`, From, To>, From, To>
  26. : Str;
  27. /** eg: type result = CamelCase<'foo-bar-baz'>, 结果:fooBarBaz */
  28. type CamelCase<S extends string> = S extends `${infer S1}-${infer S2}`
  29. ? S2 extends Capitalize<S2>
  30. ? `${S1}-${CamelCase<S2>}`
  31. : `${S1}${CamelCase<Capitalize<S2>>}`
  32. : S;
  33. /** eg: type result = StringToArray<'abc'>, 结果:['a', 'b', 'c'] */
  34. type StringToArray<S extends string, T extends any[] = []> = S extends `${infer S1}${infer S2}`
  35. ? StringToArray<S2, [...T, S1]>
  36. : T;
  37. /** `RequiredKeys`是用来获取所有必填字段,其中这些必填字段组合成一个联合类型 */
  38. type RequiredKeys<T> = {
  39. [P in keyof T]: T extends Record<P, T[P]> ? P : never;
  40. }[keyof T];
  41. /** `OptionalKeys`是用来获取所有可选字段,其中这些可选字段组合成一个联合类型 */
  42. type OptionalKeys<T> = {
  43. [P in keyof T]: {} extends Pick<T, P> ? P : never;
  44. }[keyof T];
  45. /** `GetRequired`是用来获取一个类型中,所有必填键及其类型所组成的一个新类型的 */
  46. type GetRequired<T> = {
  47. [P in RequiredKeys<T>]-?: T[P];
  48. };
  49. /** `GetOptional`是用来获取一个类型中,所有可选键及其类型所组成的一个新类型的 */
  50. type GetOptional<T> = {
  51. [P in OptionalKeys<T>]?: T[P];
  52. };
  53. /** type result1 = Includes<[1, 2, 3, 4], '4'> 结果: false; type result2 = Includes<[1, 2, 3, 4], 4> 结果: true */
  54. type Includes<T extends any[], K> = K extends T[number] ? true : false;
  55. /** eg:type result = MyConcat<[1, 2], [3, 4]> 结果:[1, 2, 3, 4]*/
  56. type MyConcat<T extends any[], U extends any[]> = [...T, ...U];
  57. /** eg: type result1 = MyPush<[1, 2, 3], 4> 结果:[1, 2, 3, 4] */
  58. type MyPush<T extends any[], K> = [...T, K];
  59. /** eg: type result3 = MyPop<[1, 2, 3]> 结果:[1, 2] */
  60. type MyPop<T extends any[]> = T extends [...infer L, infer R] ? L : never; // eslint-disable-line