typescript demo step by step
This commit is contained in:
17
06_complex/infer.ts
Normal file
17
06_complex/infer.ts
Normal file
@@ -0,0 +1,17 @@
|
||||
const arr = [1, 2, '3', 4, 5];
|
||||
// get type of array
|
||||
type GetArrItem<Arg> = Arg extends (infer Item)[] ? Item : never;
|
||||
|
||||
type ArrItem = GetArrItem<typeof arr>
|
||||
|
||||
const user = { name: 'John', age: 30 } as const;
|
||||
// get type of name property
|
||||
type GetObjectNameType<Name> = Name extends { name: infer T } ? T : never
|
||||
|
||||
type UserName = GetObjectNameType<typeof user>
|
||||
|
||||
const double = (x: number, s: 'foo') => x * 2;
|
||||
// get type of first argument of function
|
||||
type GetFirstFuncArg<Arg> = Arg extends (a, x: infer T) => any ? T : never;
|
||||
|
||||
type DoubleArgType = GetFirstFuncArg<typeof double>
|
||||
Reference in New Issue
Block a user