Index type (Keyof)

  function pluck(obj, keys) {
    return keys.map(key= > obj[key])
  }
Copy the code

Select * from obj; select * from obj; select * from obj; select * from obj; select * from obj; select * from obj; select * from obj;

  function pluck<T.K extends keyof T> (obj: T, keys: K[]) :T[K] []{
    return keys.map(key= > obj[key])
  }
  
  interface Person {
    name: string
    age: number
  }
  let person: Person = {
    name: 'Jarid'.age: 35
  }
  let strings = pluck(person, ['name'.'age'])
Copy the code

We accomplished by the generic and keyof type constraints, keyof is index type query operators, keyof T is access to a collection of all attributes of the generic type T name, in the above example is the ‘name’ | ‘age, so we can get onto the Person all of the key joint type. T[K] is a union type of index access that obtains the types of all attributes of T that exist in K.

Mapping Type (in)

  type Keys = 'name' | 'hobby'
  type Person = { [K in Keys]: string }
Copy the code

Ts in and for… In, similarly, iterates over Keys and returns the result, as in this example: js

  type Person = {
    name: string
    hobby: string
  }
Copy the code

We can combine index types and map types to implement some utility class generics, such as implementing a type that sets all the properties of the passed type to optional properties and then returns the processed type:

  type Optional<T> = {
    [P inkeyof T]? : T[P] } type Search = {name: string
      age: number
  }
  type OptionalSearch = Optional<Person>
Copy the code

[P in keyof T] is the key in T, T[P] is the type of the current key, and then we add? Make this property optional, so that when we call the generic, we make all the properties of the passed type optional and return the processed new type.

Auxiliary generic

The combination of index types and map types can be used to implement a number of very convenient generics, in fact, TS has built in some commonly used auxiliary generics.

Partial (Optional)

  /** * Make all properties in T optional */
  type Partial<T> = {
    [P inkeyof T]? : T[P] }Copy the code

Partial

makes all attributes of T optional:

  • [P in keyof T]Traversal by mapping typeTAll properties on
  • ? :Set the property to optional
  • T[P]Sets the type to the original type through index access

Required (Required)

  /** * Make all properties in T required */
  type Required<T> = {
    [P inkeyof T]-? : T[P] }Copy the code

This is the opposite of Partial, which makes all attributes of the type passed mandatory. What does that mean? Remove it, and the property naturally becomes mandatory.

Readonly

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

Readonly

makes all properties of T read-only

Exclude

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

Exclude

Exclude from T a combination of types existing in U
,>

  • By iterating throughTIf the type exists inU, the returnneverOtherwise, return the subtype, and the result isTRuled outUThe combined type after all types in.
  • neverRepresents a nonexistent type, and when combined with other types, never is removed
  • type E = Exclude<'a' | 'b' | 'd', 'b' | 'c'>, the result is:type E = 'a' | 'd'

Extract (Extract)

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

Extract < T, U > Extract also exists in the joint of type T and U type joint type The function of the generic and Exclude opposite, such as type E = Extract < ‘a’ | ‘b’ | ‘d’, ‘b’ | ‘c’ >, This time we get type E = ‘b’

Pick up

  /** * 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]
  }
Copy the code

Pick

Filters from T types that exist in K
,>

  • K extends keyof T KThe type must exist inTIn the
  • [P in K]traverseKAll types of
  • T[P]Sets the type to the original type through index access

Omit anything

  /** * 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>>
Copy the code

Omit

is to filter all properties of K from T

  • OmitIs combined withPiceandExcludeRealization, effect andPickOn the contrary
  • Through the firstExclude<keyof T, K>fromTIs excluded from a collection of index typesKAll types of
  • Then throughPickfromTFilter out all types after exclusion

Example:

  interface Coder {
    id: string,
    name: string,
    age: number,
    hobby: string[]
  }

  const JSer: Omit<Coder, 'name' | 'age'> = {
    id: '1001'.hobby: ["code"."Badminton"]}Copy the code

Record (Record)

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

Record

extends keyof any, T> extends keyof any, T>

  interface Obj {
    title: string,
    value: number
  }
  
  const List: Record<string, Obj> = {
    home: { title: 'home'.value: 1 },
    search: { title: 'search'.value: 2}}Copy the code

ReturnType (return value type)

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

ReturnType

any> Returns the return type of the passed function type T

  • T extends (... args: any) => anyThe constraint parameterTMust be a function type
  • inferThe function of keywords is to allow TS to derive the type itself and store the derived results ininferThe following parameter type
  • inferKeywords can only be used inextendsCondition type
  • The way to do that is to judge firstTIs the function type and derives the return value type stored inRIf yes, returnRIf not, returnnever