Master the types of TS tools, so that you can develop with half the effort

1, Type alias

TypeScript provides a convenient syntax for setting aliases for type annotations. You can use type SomeName = someValidTypeAnnotation to create aliases, such as:

type Pet = 'cat' | 'dog';
let pet: Pet;

pet = 'cat'; // Ok
pet = 'dog'; // Ok
pet = 'zebra'; // Compiler error

 

2, Basic knowledge

In order to better understand and master TypeScript built-in type aliases, let's introduce some basic knowledge.

2.1 typeof

In TypeScript, the typeof operator can be used to get the type of a variable declaration or object.

interface Person {
  name: string;
  age: number;
}

const sem: Person = { name: 'semlinker', age: 30 };
type Sem= typeof sem; // -> Person

function toArray(x: number): Array<number> {
  return [x];
}

type Func = typeof toArray; // -> (x: number) => number[]

 

2.2 keyof

The keyof operator can be used for all key values in an object:

interface Person {
    name: string;
    age: number;
}

type K1 = keyof Person; // "name" | "age"
type K2 = keyof Person[]; // "length" | "toString" | "pop" | "push" | "concat" | "join" 
type K3 = keyof { [x: string]: Person };  // string | number

 

2.3 in

in to traverse enumeration types:

type Keys = "a" | "b" | "c"

type Obj =  {
  [p in Keys]: any
} // -> { a: any, b: any, c: any }

 

2.4 infer

In a conditional type statement, you can declare a type variable with infer and use it.

type ReturnType<T> = T extends (
  ...args: any[]
) => infer R ? R : any;

 

In the above code, infer R is to declare a variable to carry the return value type of the incoming function signature. In short, it is convenient to use it to get the return value type of the function.

2.5 extends

Sometimes the generics we define don't want to be too flexible or inherit some classes. You can add generic constraints through the extends keyword.

interface ILengthwise {
  length: number;
}

function loggingIdentity<T extends ILengthwise>(arg: T): T {
  console.log(arg.length);
  return arg;
}

 

Now that the generic function has constraints defined, it is no longer applicable to any type:

loggingIdentity(3);  // Error, number doesn't have a .length property

 

At this time, we need to pass in a value conforming to the constraint type, which must contain the required properties:

loggingIdentity({length: 10, value: 3});

 

3, Built in type alias

3.1 Partial

The function of partial < T > is to change all attributes in a certain type into optional items.

definition:

// node_modules/typescript/lib/lib.es5.d.ts

/**
 * Make all properties in T optional
 */
type Partial<T> = {
    [P in keyof T]?: T[P];
};

 

In the above code, first get all the attribute names of T through keyof T, then use in to traverse, assign the value to P, and finally get the corresponding attribute value through T[P]. The middle "? Is used to make all attributes optional.

Example:

interface Todo {
  title: string;
  description: string;
}

function updateTodo(todo: Todo, fieldsToUpdate: Partial<Todo>) {
  return { ...todo, ...fieldsToUpdate };
}

const todo1 = {
  title: "organize desk",
  description: "clear clutter"
};

const todo2 = updateTodo(todo1, {
  description: "throw out trash"
});

 

3.2 Required

The function of required < T > is to change all the attributes in a certain type into required options.

definition:

// node_modules/typescript/lib/lib.es5.d.ts

/**
 * Make all properties in T required
 */
type Required<T> = {
    [P in keyof T]-?: T[P];
};

 

In the above code, the function of - is to remove the optional item.

Example:

interface Props {
  a?: number;
  b?: string;
}

const obj: Props = { a: 5 }; // OK
const obj2: Required<Props> = { a: 5 }; // Error: property 'b' missing

 

3.3 Readonly

Readonly < T > is used to change all properties of a type to read-only properties, which means that these properties cannot be reassigned.

definition:

// node_modules/typescript/lib/lib.es5.d.ts

/**
 * Make all properties in T readonly
 */
type Readonly<T> = {
    readonly [P in keyof T]: T[P];
};

 

If the above readonly is changed to - readonly, the readonly ID of the child property is removed.

Example:

interface Todo {
  title: string;
}

const todo: Readonly<Todo> = {
  title: "Delete inactive users"
};

todo.title = "Hello"; // Error: cannot reassign a readonly property

 

Readonly < T > is useful for expressions that fail to assign values at run time (for example, when trying to reassign the properties of a frozen object).

function freeze<T>(obj: T): Readonly<T>;

 

3.4 Record

The function of record < K extends keyof any, t > is to convert the values of all attributes in K to T type.

definition:

// node_modules/typescript/lib/lib.es5.d.ts

/**
 * Construct a type with a set of properties K of type T
 */
type Record<K extends keyof any, T> = {
    [P in K]: T;
};

 

Example:

interface PageInfo {
  title: string;
}

type Page = "home" | "about" | "contact";

const x: Record<Page, PageInfo> = {
  about: { title: "about" },
  contact: { title: "contact" },
  home: { title: "home" }
};

 

3.5 Pick

The function of pick < T, K extends keyof T > is to pick out the sub attributes of a type and change them into the sub types containing the partial attributes of the type.

definition:

// node_modules/typescript/lib/lib.es5.d.ts

/**
 * From T, pick a set of properties whose keys are in the union K
 */
type Pick<T, K extends keyof T> = {
    [P in K]: T[P];
};

 

Example:

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}

type TodoPreview = Pick<Todo, "title" | "completed">;

const todo: TodoPreview = {
  title: "Clean room",
  completed: false
};

 

3.6 Exclude

The function of exclude < T, u > is to remove one type from another.

definition:

// node_modules/typescript/lib/lib.es5.d.ts

/**
 * Exclude from T those types that are assignable to U
 */
type Exclude<T, U> = T extends U ? never : T;

 

If t can be assigned to the U type, then it will return the never type, otherwise it will return the T type. The final effect is to remove some types of u from t.

Example:

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

 

3.7 Extract

Extract < T, U > is to extract U from t.

definition:

// node_modules/typescript/lib/lib.es5.d.ts

/**
 * Extract from T those types that are assignable to U
 */
type Extract<T, U> = T extends U ? T : never;

 

If T can be assigned to U type, then T type will be returned; otherwise, never type will be returned.

Example:

type T0 = Extract<"a" | "b" | "c", "a" | "f">; // "a"
type T1 = Extract<string | number | (() => void), Function>; // () => void

 

3.8 Omit

The function of omit < T, K extends keyof any > is to construct a new type by using all attributes of type T except type K.

definition:

// node_modules/typescript/lib/lib.es5.d.ts

/**
 * Construct a type with the properties of T except for those in type K.
 */
type Omit<T, K extends keyof any> = Pick<T, Exclude<keyof T, K>>;

 

Example:

interface Todo {
  title: string;
  description: string;
  completed: boolean;
}

type TodoPreview = Omit<Todo, "description">;

const todo: TodoPreview = {
  title: "Clean room",
  completed: false
};

 

3.9 NonNullable

The function of nonnullable < T > is to filter the null and undefined types in the type.

definition:

// node_modules/typescript/lib/lib.es5.d.ts

/**
 * Exclude null and undefined from T
 */
type NonNullable<T> = T extends null | undefined ? never : T;

 

Example:

type T0 = NonNullable<string | number | undefined>; // string | number
type T1 = NonNullable<string[] | null | undefined>; // string[]

 

3.10 ReturnType

ReturnType < T > is used to get the return type of function t.

definition:

// node_modules/typescript/lib/lib.es5.d.ts

/**
 * Obtain the return type of a function type
 */
type ReturnType<T extends (...args: any) => any> = T extends (...args: any) => infer R ? R : any;

 

Example:

type T0 = ReturnType<() => string>; // string
type T1 = ReturnType<(s: string) => void>; // void
type T2 = ReturnType<<T>() => T>; // {}
type T3 = ReturnType<<T extends U, U extends number[]>() => T>; // number[]
type T4 = ReturnType<any>; // any
type T5 = ReturnType<never>; // any
type T6 = ReturnType<string>; // Error
type T7 = ReturnType<Function>; // Error

 

3.11 InstanceType

The role of InstanceType is to get the instance type of constructor type.

definition:

// node_modules/typescript/lib/lib.es5.d.ts

/**
 * Obtain the return type of a constructor function type
 */
type InstanceType<T extends new (...args: any) => any> = T extends new (...args: any) => infer R ? R : any;

 

Example:

class C {
  x = 0;
  y = 0;
}

type T0 = InstanceType<typeof C>; // C
type T1 = InstanceType<any>; // any
type T2 = InstanceType<never>; // any
type T3 = InstanceType<string>; // Error
type T4 = InstanceType<Function>; // Error

 

3.12 ThisType

Thistype < T > is used to specify the type of context object.

definition:

// node_modules/typescript/lib/lib.es5.d.ts

/**
 * Marker for contextual 'this' type
 */
interface ThisType<T> { }

 

Note: when using thistype < T > you must ensure that the -- noImplicitThis flag is set to true.

Example:

interface Person {
    name: string;
    age: number;
}

const obj: ThisType<Person> = {
  dosth() {
    this.name // string
  }
}

 

3.13 Parameters

Parameters < T > is used to get the tuple type composed of the parameter types of the function.

definition:

// node_modules/typescript/lib/lib.es5.d.ts

/**
 * Obtain the parameters of a function type in a tuple
 */
type Parameters<T extends (...args: any) => any> = T extends (...args: infer P) => any 
  ? P : never;

 

Example:

type A = Parameters<() => void>; // []
type B = Parameters<typeof Array.isArray>; // [any]
type C = Parameters<typeof parseInt>; // [string, (number | undefined)?]
type D = Parameters<typeof Math.max>; // number[]

 

3.14 ConstructorParameters

The role of constructorparameters < T > is to extract all parameter types of constructor type. It generates a tuple type with all parameter types (or never if t is not a function).

definition:

// node_modules/typescript/lib/lib.es5.d.ts

/**
 * Obtain the parameters of a constructor function type in a tuple
 */
type ConstructorParameters<T extends new (...args: any) => any> = T extends new (...args: infer P) => any ? P : never;

 

Example:

type A = ConstructorParameters<ErrorConstructor>; // [(string | undefined)?]
type B = ConstructorParameters<FunctionConstructor>; // string[]
type C = ConstructorParameters<RegExpConstructor>; // [string, (string | undefined)?]

 

Original https://semlinker.com/ts-utility-types/

Tags: TypeScript Attribute

Posted on Sat, 16 May 2020 00:32:42 -0400 by sickness01