Skip to main content

Advanced usage of TypeScript(三)

· 3 min read

This article introduces the advanced uses of TypeScript. it introduces TypeScript from the perspectives of generics helper.

Partial<T>

Partial<T> make all properties in a generic optional.

type Partial<T> = {
[P in keyof T]?: T[P]
}

For example:

type Animal = {
name: string,
category: string,
age: number,
eat: () => number,
};

with Partial<Animal>:

type PartOfAnimal = Partial<Animal>;
const ww: PartOfAnimal = { name: "jstyro" };

Record<K, T>

Record<K, T> will convert all attribute values in K to type T, which we use to declare a normal object.

type Record<K extends keyof any,T> = {
[key in K]: T
}

keyof any corresponding types for the number | string | symbol, the type of collection object keys.

const obj: Record<string, string> = { name: "jstyro", tag: "website" };

Pick<T, K>

Pick<T, K> will pick the properties in K from T.

type Pick<T, K extends keyof T> = {
[P in K]: T[P]
}
type Animal = {
name: string,
category: string,
age: number,
eat: () => number,
};
const bird: Pick<Animal, "name" | "age"> = { name: "jstyro", age: 18 };

Omit<T, K>

The Omit utility is the opposite of the Pick type. And instead of selecting elements, it will remove K properties from the type T.

const OmitAnimal: Omit<Animal, "name" | "age"> = {
category: "lion",
eat: () => {
console.log("eat");
},
};

Exclude<T, K>

Exclude<T, K> will exclude the properties in K from T.

type Exclude<T, U> = T extends U ? never : T

The Exclude utility will construct a type by excluding properties that are already present in two different types. It excludes from T all fields that are assignable to U.

type T1 = Exclude<"a" | "b" | "c", "a" | "b">; // "c"
type T2 = Exclude<string | number | (() => void), Function>; // string | number

ReturnType<T>

ReturnType<T> will return the return type of a function.

type ReturnType<T extends (...args: any) => any>
= T extends (...args: any) => infer R ? R : any;
function foo(x: string | number): string | number {
/*..*/
}
type FooType = ReturnType<foo>; // string | number

utility-types

Collection of utility types, complementing TypeScript built-in mapped types and aliases (think "lodash" for static types). utility-types