Use a more readable way to set TypeScript types

Posted by zarp on Tue, 01 Feb 2022 21:17:54 +0100

Author: SARANSH KATARIA
Translator: front end Xiaozhi
Source: wisdomgeek

There are dreams and dry goods. Wechat search [Daqian world] pays attention to this dish washing wisdom who is still washing dishes in the early morning.

This article GitHub https://github.com/qq449245884/xiaozhi It has been included. There are complete test sites, materials and my series of articles for the interview of front-line large factories.

TypeScript provides some built-in practical types, which can better convert types from one form to another.

These built-in types are available globally, so you can easily use them.

TypeScript generics

Type aliases and generics are important before understanding TypeScript utilities and types. We create a type alias for any existing type in TypeScript.

type MyString = string;

let helloWorldMessage: MyString = 'Hello Wisdom Geek';

Generics are used to create reusable type aliases. Suppose we have an identity function that returns any value passed:

const identity = (arg: string): string => arg;

What if we want to return the number type? Some small partners may use any instead of a specific type

const identity = (arg: any): any => arg;

However, this reduces the type information of parameters and therefore loses the benefits of TypeScript. We want to capture the types of parameters in a way that can be used to represent the return type. This is where generics come in handy. We will use type variables that apply to types instead of values.

const identity<T> = (arg: T): T => arg;

Next, specify the type of function when calling it:

const output = identity<string>("Hello Wisdom Geek");

Built in utility types in TypeScript

Before we start talking about built-in utility types, these tool types are available before version 4.0 and do not require any additional packages.

Partial

Primary < T > makes all attributes of T optional.

type BlogPost = {
  title: string;
  author: string;
}

type PartialBlogPost = Partial<BlogPost>;
/* Equivalent to{
  title?: string;
  author?: string;
} */

Required

Required < T > make all attributes of T mandatory.

type PartialBlogPost = {
  title?: string;
  author?: string;
}

type BlogPost = Required<PartialBlogPost>;
/* Equivalent to{
  title: string;
  author: string;
} */

Readonly

Readonly < T > changes all attributes of t to read-only.

type BlogPost = {
  title: string;
  author: string;
}

type BlogPost = Readonly<PartialBlogPost>;
/* Equivalent to{
  readonly title: string;
  readonly author: string;
} */

Pick

Pick < T, k > extract the attributes in t from K

type Point3D = {
  x: number,
  y: number,
  z: number,
};


type Point2D = Pick<Point3D, 'x'|'y'>;
/* Equivalent to{
  x: number,
  y: number
} */


Parameters

Parameters < T > t is Function, and the return value in the extraction Function is tuple.

type T0 = Parameters<() => string>;
// type T0 = []

type T1 = Parameters<(s: string) => void>; 
// type T1 = [s: string]

type T2 = Parameters<<T>(arg: T) => T>;
// type T2 = [arg: unknown]


Omit

Omit < T, k > is the opposite of Pick (removing attributes)

type Point3D = {
  x: number,
  y: number,
  z: number,
};


type Point2D = Omit<Point3D, 'z'>;
/* same as {
  x: number,
  y: number
} */

Record

Record < K, t > generates an interface. The attributes are all attributes of K, and all attributes of K have the type of T

type BlogPost = Record<'title' | 'author', strnig>

/* same as {
  title: string;
  author: string;
} */

If all types have the same value, the declared version of Record is more concise and readable because they all have the same type.

Extract

Extract < T, u > - used to extract members of type t that can be assigned to type U

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

Exclude

Exclude < T, u > - used to remove members from type t that are not in type U.

type T0 = Exclude<"a" | "b" | "c", "a">;
     // type T0 = "b" | "c"

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

NonNullable

Nonnullable < T > - used to remove undefined and null types from type T.

type T0 = NonNullable<string | number | undefined>;
     // type T0 = string | number

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

ReturnType

ReturnType < T > - get the return type of function type

type T0 = ReturnType<() => string>;
     
type T0 = string
type T1 = ReturnType<(s: string) => void>;
     
type T1 = void
type T2 = ReturnType<<T>() => T>;
     
type T2 = unknown
type T3 = ReturnType<<T extends U, U extends number[]>() => T>;
     
type T3 = number[]

type T5 = ReturnType<any>;
     
type T5 = any
type T6 = ReturnType<never>;
     
type T6 = never
type T7 = ReturnType<string>;

InstanceType

Instancetype < T > - get the instance type of the constructor

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

type T0 = InstanceType<typeof C>;
     
type T0 = C
type T1 = InstanceType<any>;
     
type T1 = any
type T2 = InstanceType<never>;
     
type T2 = never

~After that, I'm Xiao Zhi. I've gone to teach my little sister.

For more practical categories, please see the official website.
https://www.typescriptlang.org/docs/handbook/utility-types.html#uppercasestringtype

The bugs that may exist after the code is deployed cannot be known in real time. Afterwards, in order to solve these bugs, we spent a lot of time on log debugging. By the way, we recommend a useful BUG monitoring tool Fundebug.

Original text: https://www.wisdomgeek.com/development/web-development/typescript/using-utility-types-for-transforming-typescript-types/

communication

The article is continuously updated every week. You can search * * [Daqian world] on wechat to read it for the first time and reply to [welfare] * * there are many front-end videos waiting for you. This article GitHub https://github.com/qq449245884/xiaozhi Already included, welcome Star.

Topics: Javascript Front-end React