typescript cheatsheet

Complex typescript type implement

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
// Tuple
type Tuple = [number, string];

// Object
interface IPerson {
name: string;
age: number;
}

class Person implements IPerson {
name: string;
age: number;
}

const person: IPerson = {
name: "Jay",
age: 43,
};

// Function
interface SayHello {
(name: string): string;
}

const func: SayHello = (name: string) => {
return "hello," + name;
};

// Constructor
interface PersonConstructor {
new (name: string, age: number): IPerson;
}

function createPerson(ctor: PersonConstructor): IPerson {
return new ctor("Jay", 43);
}

// enum
enum Color {
RED = "red",
YELLOW = "Yellow",
BLUE = "blue",
}

const color = Color.RED;

// void
type v = void;

// never
type nv = never;
type nv_and_str1 = never & "123";
type nv_and_str2 = `${never}${"123"}`;
type nv_and_num1 = never & 321;
type nv_and_num2 = `${never}${1}`;

// any
type a = any;

// unknown
type uk = unknown;

// Decorate
interface IAnimal {
name: string;
weight?: number; //optional
}

// Condition
type res = 1 extends 2 ? true : false;

type isTwo<T> = T extends 2 ? true : false;

type one = isTwo<1>;

type two = isTwo<2>;

// String
// add
type first_name = "Jay";
type last_name = "Chou";
type the_man = `${first_name} ${last_name}`;

// Infer
// get part of str
type name = "Jay,Chou";
type surname = name extends `Jay,${infer rest}` ? rest : never;
type jay = name extends `${infer x},${infer y}` ? x : never;

// like regex but more flexible
// match the exact shape
// get first element of array
type First<Tuple extends unknown[]> = Tuple extends [infer T, ...infer R]
? T
: never;

type getFirst = First<[1, 2, 3]>; // type getFirst = 1
type getFirst2 = First<[]>; // type getFirst2 = never

type Second<Tuple extends unknown[]> = Tuple extends [any, infer T, ...infer R]
? T
: never;

type getSec = Second<[1, 2, 3]>; // type getSec = 2

// get last element of array
type Last<Arr extends unknown[]> = Arr extends [...any, infer T] ? T : never;
// output: type getLast = 3
type getLast = Last<[1, 2, 3]>;

// get rest element of array
type Rest<Arr extends unknown[]> = Arr extends [...infer R, unknown]
? R
: never;

// output: type getRest = [1, 2]
type getRest = Rest<[1, 2, 3]>;

type Rest2<Arr extends unknown[]> = Arr extends [unknown, ...infer R]
? R
: never;

// output: type getRest = [2, 3]
type getRest2 = Rest2<[1, 2, 3]>;

// array
type arr = unknown[];

// or
type a_or_b = 1 | 2;

// merge same type
type ObjType = { a: number } & { b: boolean };

type o = { a: number; b: boolean } extends ObjType ? true : false; // type o = true

// invaild->never
type ee = "str" & 100; // type ee = never

// object
type person = {
name: "jay";
age: 43;
};
type values = person[keyof person]; // type values = "jay" | 43

type person2 = {
[key in keyof person]: person[key];
};

type MapType<T> = {
[Key in keyof T]?: [T[Key], T[Key], "new CD!"];
};

type mt = MapType<{ name: "jay"; age: 43 }>;

type MapType2<T> = {
[Key in keyof T as `${Key & string}${Key & string}`]: [
T[Key],
T[Key],
T[Key]
];
};
type mt2 = MapType2<{ name: "jay"; age: 43 }>;

// StartsWith
type StartsWith<
Str extends string,
Perfix extends string
> = Str extends `${Perfix}${string}` ? true : false;

// output: type sw = true
type sw = StartsWith<"Jay Chou", "Jay">;

// output: type sw2 = false
type sw2 = StartsWith<"Jay Chou", "Lin">;

// Replace string
type Replace<
Str extends string,
From extends string,
To extends string
> = Str extends `${infer P}${From}${infer S}` ? `${P}${To}${S}` : Str;

// output: type rp = "Jay Zhou"
type rp = Replace<"Jay Shou", "S", "Z">;
type rp2 = Replace<"Jay Shou", "X", "S">;

// Trim
// Trim right
// use recursive
type TrimRight<Str extends string> = Str extends `${infer Rest}${
| " "
| "\n"
| "\t"}`
? TrimRight<Rest>
: Str;

type tr = TrimRight<"Jay Zhou ">;

// trim left
type TrimLeft<Str extends string> = Str extends `${
| " "
| "\n"
| "\t"}${infer Rest}`
? TrimLeft<Rest>
: Str;

type tl = TrimLeft<" Jay Zhou">;

// trim = TrimRight&TrimLeft
// output: type tm = "Jay Zhou"
type tm = TrimRight<
TrimLeft<`
Jay Zhou

`>
>;

// function
// get args of fucntion
function createCD(name: string, price: number) {
return { name, price, author: "Jay Chou" };
}

// match: (x)=>y
type GetArgsOfFunc<Func extends Function> = Func extends (
...args: infer Args
) => unknown
? Args
: never;

// type gaf = [name: string, price: number]
type gaf = GetArgsOfFunc<typeof createCD>;

type GetArgsOfFunc2<Func extends Function> = Func extends (
aa: infer A,
bb: infer B
) => unknown
? [A, B]
: never;

// type gaf2 = [string, number]
type gaf2 = GetArgsOfFunc2<typeof createCD>;

// get return of function
type GetReturnOfFunc<Func extends Function> = Func extends (
...args
) => infer Return
? Return
: never;

// type grf = { name: string; price: number; author: string; }
type grf = GetReturnOfFunc<typeof createCD>;

// type grf2 = "J"
type grf2 = GetReturnOfFunc<() => "J">;

// array
type Push<Arr extends unknown[], Ele> = [...Arr, Ele];

// output: type pushRes = [1, 2, 3, 4]
type pushRes = Push<[1, 2, 3], 4>;

// Unshift
type Unshift<Arr extends unknown[], Ele> = [Ele, ...Arr];

// output: type unshiftRes = [4, 1, 2, 3]
type unshiftRes = Unshift<[1, 2, 3], 4>;

// Zip
// type tuple1 = [1,2];
// type tuple2 = ['Jay Chou', 'Lin Junjie'];
// type tuple = [[1, 'Jay Chou'], [2, 'Lin Junjie']];

// fixed parameter
type Zip<
Arr1 extends [unknown, unknown],
Arr2 extends [unknown, unknown]
> = Arr1 extends [infer v1_1, infer v1_2]
? Arr2 extends [infer v2_1, infer v2_2]
? [[v1_1, v2_1], [v1_2, v2_2]]
: []
: [];

// type zipRes = [[1, "Jay Chou"], [2, "Lin Junjie"]]
type zipRes = Zip<[1, 2], ["Jay Chou", "Lin Junjie"]>;

// adaptive parameter
type Zip2<Arr1 extends unknown[], Arr2 extends unknown[]> = Arr1 extends [
infer v1_1,
...infer Rest1
]
? Arr2 extends [infer v2_1, ...infer Rest2]
? [[v1_1, v2_1], ...Zip2<Rest1, Rest2>]
: []
: [];

// type zip2Res = [[1, "Jay Chou"], [2, "Lin Junjie"], [3, "Mikael J"]]
type zip2Res = Zip2<[1, 2, 3], ["Jay Chou", "Lin Junjie", "Mikael J"]>;

// CapitializeStr
type CapitializeStr<Str extends string> =
Str extends `${infer First}${infer Rest}`
? `${Uppercase<First>}${Rest}`
: Str;

// output: type capitializeStrRes = "Jay"
type capitializeStrRes = CapitializeStr<"jay">;

// hi_jay_chou ==> HiJayChou
type CamelCase<Str extends string> = Str extends `${infer first}_${infer rest}`
? `${CapitializeStr<first>}${CamelCase<rest>}`
: CapitializeStr<Str>;

// type camelCaseRes = "HiJayChou"
type camelCaseRes = CamelCase<"hi_jay_chou">;

// hi_jay_chou ==> hiJayChou
// hi_j ay_c hou
type CamelCase2<Str extends string> =
Str extends `${infer first}_${infer right}${infer rest}`
? `${first}${Uppercase<right>}${CamelCase2<rest>}`
: Str;

// type camelCaseRes2 = "hiJayChou"
type camelCaseRes2 = CamelCase2<"hi_jay_chou">;

// append arg to function
type AppendArgument<Func extends Function, Arg> = Func extends (
...args: infer Args
) => infer ReturnType
? (...args: [...Args, Arg]) => ReturnType
: never;

// type appendArgumentRes = (args_0: string, args_1: number) => void
type appendArgumentRes = AppendArgument<(name: string) => void, number>;

// as
type UppercaseKey<Obj extends object> = {
[Key in keyof Obj as Uppercase<Key & string>]: Obj[Key];
};

// type cd = { NAME: string; PRICE: number; }
type cd = UppercaseKey<{ name: string; price: number }>;

// Record<string, any> ==> object

// toReadonly: add readonly
type ToReadonly<T extends Record<string, any>> = {
readonly [key in keyof T]: T[key];
};

// type toReadonlyRes = { readonly name: "chopin"; readonly price: 99; }
type toReadonlyRes = ToReadonly<{ name: "chopin"; price: 99 }>;

// ToPartial
type ToPartial<T> = {
[key in keyof T]?: T[key];
};

// type toReadonlyToPartialRes = { name?: "chopin"; price?: 99; }
type toReadonlyToPartialRes = ToPartial<{ name: "chopin"; price: 99 }>;

// toMutable: remove readonly
type ToMutable<T> = {
-readonly [key in keyof T]: T[key];
};

// type toMutableRes = { name: "chopin"; price: 99; }
type toMutableRes = ToMutable<{ readonly name: "chopin"; readonly price: 99 }>;

// ToRequired
type ToRequired<T> = {
[key in keyof T]-?: T[key];
};
// type toRequiredRes = { name: "chopin"; price: 99; }
type toRequiredRes = ToRequired<{ name?: "chopin"; price?: 99 }>;

// filter props by value type
type Filter<Obj extends Record<string, any>, ValueType> = {
[key in keyof Obj as ValueType extends Obj[key] ? key : never]: Obj[key];
};

interface CD {
name: string;
price: number;
artists: string[];
}
// type FilterRes = { name: string; price: number; }
type FilterRes = Filter<CD, string | number>;

// IsEqual
type IsEqual<A, B> = (A extends B ? true : false) &
(B extends A ? true : false);
type isEqualRes = IsEqual<1, 1>;
type isEqualRes2 = IsEqual<{ name: "jay" }, { name: "jay" }>;

// IsInclude
type IsInclude<Arr extends unknown[], Item> = Arr extends [
infer First,
...infer Rest
]
? IsEqual<First, Item> extends true
? true
: IsInclude<Rest, Item>
: false;

//type isIncludeRes = true
type isIncludeRes = IsInclude<[1, 2, 3], 1>;

//type isIncludeRes = false
type isIncludeRes2 = IsInclude<[1, 2, 3], 4>;

// RemoveItem
type RemoveItem<
Arr extends unknown[],
Item,
Res extends unknown[] = []
> = Arr extends [infer First, ...infer Rest]
? IsEqual<First, Item> extends true
? RemoveItem<Rest, Item, Res>
: RemoveItem<Rest, Item, [...Res, First]>
: Res;

// type removeItemRes = [2, 3]
type removeItemRes = RemoveItem<[1, 2, 1, 3, 1], 1>;

//type removeItemRes2 = [1, 2, 3]
type removeItemRes2 = RemoveItem<[1, 2, 3], 4>;

// Replace All
// from begin to end
type ReplaceAll<
Str extends string,
From extends string,
To extends string
> = Str extends `${infer First}${infer Rest}`
? IsEqual<First, From> extends true
? `${To}${ReplaceAll<Rest, From, To>}`
: `${First}${ReplaceAll<Rest, From, To>}`
: Str;

// pattern match
type ReplaceAll2<
Str extends string,
From extends string,
To extends string
> = Str extends `${infer Left}${From}${infer Rest}`
? `${Left}${To}${ReplaceAll<Rest, From, To>}`
: Str;

// type replaceAllRes = "Jay"
type replaceAllRes = ReplaceAll<"1J1a1y", "1", "">;
type replaceAllRes2 = ReplaceAll2<"1J1a1y", "1", "">;

// string union
type StrUnion<Str extends string> = Str extends `${infer First}${infer Rest}`
? First | StrUnion<Rest>
: never;

// type strUnionRes = "J" | "a" | "y"
type strUnionRes = StrUnion<"Jay">;

// ReverseStr
type ReverseStr<Str extends string> = Str extends `${infer First}${infer Rest}`
? `${ReverseStr<Rest>}${First}`
: Str;

// type reverseStrRes = "Jay"
type reverseStrRes = ReverseStr<"yaJ">;

// deep readonly
type DeepReadonly<Obj extends Record<string, any>> = {
readonly [Key in keyof Obj]: Obj[Key] extends object
? DeepReadonly<Obj[Key]>
: Obj[Key];
};

const deepObj = { a: { b: { c: "1", d: "2" } } };

type DeepReadonlyRes = DeepReadonly<typeof deepObj>;
type DeepReadonlyResA = DeepReadonly<typeof deepObj>["a"];
type DeepReadonlyResAB = DeepReadonly<typeof deepObj>["a"]["b"];

// Math
type NumTwo = [any, any]["length"];

// ADD in ts is like arr1.length + arr2.length
type BuildArr<
Len extends number,
Arr extends unknown[] = []
> = Arr["length"] extends Len ? Arr : BuildArr<Len, [...Arr, unknown]>;

// type Len2Array = [unknown, unknown]
type Len2Array = BuildArr<2>;

type Add<Num1 extends number, Num2 extends number> = [
...BuildArr<Num1>,
...BuildArr<Num2>
]["length"];

// type add1And2 = 3
type add1And2 = Add<1, 2>;

// Sub
type Sub<Num1 extends number, Num2 extends number> = BuildArr<Num1> extends [
...BuildArr<Num2>,
...infer Rest
]
? Rest["length"]
: never;

// type subOneTwo = 3
type subOneTwo = Sub<4, 1>;

type Subtract<
Num1 extends number,
Num2 extends number
> = BuildArr<Num1> extends [...arr1: BuildArr<Num2>, ...arr2: infer Rest]
? Rest["length"]
: never;

// type subOneTwo2 = 1
type subOneTwo2 = Subtract<2, 1>;

Author

David Lv

Posted on

2022-02-20

Updated on

2022-07-15

Licensed under