TypeScript Type-Exercises 1
3 Jan, 2024
- Template String
type URL:`https://${string}:${port}`
let a1:URL = 'https://google.com:443' // ok
let a2:URL = 'https://test' // error
Get the return type of the function
type ReturnType<T> = T extends (...args: any[]) => infer R ? R : any;
type T2 = ReturnType<() => string>; // T2 = string
const sum = (a: number, b: number): number => a + b;
type T3 = ReturnType<sum>; // T3 = number
Get the parameters type list
type Parameters<T extends (...args: any[]) => any> = T extends (...args: infer P) => any ? P : never;
type Func = (a: number, b: string) => void;
type Params = Parameters<Func>;
// Params = [number, string]
Note: For above two examples they showed the keyword infer's usage.
Namely you can treat them as a variable that contain the correspond type.
For example, in type Parameters<T extends (...args: any[]) => any> = T extends (...args: infer P) => any ? P : never , the infer P means storing the types of ...args into P and assigns P's value to the Parameters if T is an function.
Restrict the variable equals to one of the elements in an Tuple
const myTuple = ["a", 100, false] as const;
type MyType = (typeof myTuple)[number];
let myVar: MyType;
// myVar could only be 'a', 100 or false
Note: In this example the myTuple was perceived an readonly tuple and every element are its literal type, namely the first element is the 'a' type rather then string. If you want to make MyType = string | number | boolean you can remove the as const assertion.
Equal to the first element in a specified tuple.
type First<T extends any[]> = T extends [infer F, ...infer R] ? F : never;
type MyType = First<["a", 100, false]>;
// MyType = 'a'
Awaited. Get the type T of Promise<T>
type Awaited<T extends Promise<any>> = T extends PromiseLike<infer L> ? L : never;
const asyncFunc = async () => {
return true;
};
type MyType = Awaited<asyncFunc>;
// MyType = boolean.