Burst the liver overnight just to send it to you. Write a quick TypeScript guide to the primary front-end

1, Why use TypeScript

TypeScript allows us to avoid some types or code results that are not what we expect. xxx is not defined. We all know that JavaScript errors are thrown during operation, but TypeScript errors are directly told to us in the editor, which greatly improves the development efficiency, does not need to spend a lot of time writing single tests, and avoids a lot of time checking bugs.

2, Advantages and disadvantages of TypeScript

advantage

  • Generally, when we perform front and rear joint debugging, we need to look at the field types in the interface document, and TypeScript will automatically help us identify the current type. It saves us time to read documents or network. This is called type derivation (we'll talk about it later)

  • Friendly prompt errors in the editor to avoid stepping on the pit of implicit type conversion at run time.

shortcoming

  • There is a certain learning cost. There are several type concepts in TypeScript, such as interface interface, class class class, enum enumeration, generics generics, etc., which require us to spend time learning.

  • It may not be perfectly combined with some plug-in libraries

3, TypeScript running process and JavaScript code running process

1. The JavaScript running process is as follows, which depends on NodeJs environment and browser environment

  • Convert JavaScript code to JavaScript AST
  • Convert AST code to bytecode
  • Calculate bytecode during operation

2. TypeScript operation process. The following operations are TSC operations. After three steps, continue the same operation as above and let the browser parse

  • Compile TypeScript code into TypeScript ast
  • Check type check on AST code
  • After type checking, it is compiled into JavaScript code
  • Convert JavaScript code to JavaScript AST
  • Convert AST code to bytecode
  • Calculate bytecode during operation

4, The difference between TypeScript and JavaScript

Only by understanding the difference between the two can we better understand TypeScript

Type system propertiesJavaScriptTypeScript
How are types bound?dynamicstatic state
Is there an implicit type conversion?yesno
When to check the type?RuntimeCompile time
When to report errorsRuntimeCompile time

Type binding

JavaScript

JavaScript dynamically binds types. Only the running program can know the type. JavaScript knows nothing about the type before the program runs

TypeScript

TypeScript will know the current type before the program runs (that is, at compile time). Of course, if the variable has no type defined, TypeScript will automatically deduce the type.

Type conversion

JavaScript

For example, in a code fragment such as 1 + true in JavaScript, there is an implicit conversion in JavaScript. At this time, true will become the type of number, and number(true) and 1 will be added.

TypeScript

In TypeScript, codes such as 1+true will report errors in TypeScript, suggesting that number type cannot operate with boolean type.

When to check type

JavaScript

In JavaScript, types can only be checked when the program is running. Type also has implicit conversion, which is very difficult.

TypeScript

In TypeScript, the type will be checked during compilation. If it does not match the expected type, an error will be reported in the editor

When to report errors

JavaScript

In JavaScript, exceptions can be thrown only when the program is executed. JavaScript has implicit conversion. When the program is executed, we can really know whether the code type is the expected type and whether the code is valid.

TypeScript

In TypeScript, when you write code in the editor, if there is an error, you will directly throw an exception, which greatly improves the efficiency and convenience.

5, TypeScript expands around two patterns in total

Explicit annotation type

Take a chestnut

let name: string = "Front end entertainment circle";

let age: number = 38;

let hobby: string[] = ["write code", "play a game"]

The explicit annotation type is to define the type when declaring the variable (the official discourse is to bring the annotation when declaring). Let's see at a glance that oh ~, this name is a string type.

Derivation type

Take a chestnut

let name = "Front end entertainment circle"; // Is a string type

let age = 38;  // Is a number type

let hobby = ["write code", "play a game"] // Is a string array type

Derivation type is to remove the display annotation, and the system will automatically identify the type of the current value.

6, Install typescript & & run

typescript

The typescript environment is installed globally.

npm i -g typescript

But this is only typescript installed. How do we run it ts file. After installing typescript, we can execute the tsc command.

Our file is called index TS, execute tsc index directly on the command line TS is enough. Then you can see an index compiled in the directory JS, which is the result of tsc compilation.

index.ts

const userName: string = "Front end entertainment circle" 

Run TSC index TS, you can see in index Another index is generated under the same level of TS JS, the following is the compiled result file index js.

var userName = "Front end entertainment circle"

As we know above, running the tsc command can compile and generate a file. Some friends think it's too troublesome. Each time they run, they just compile a file, but they don't run it. They have to use node index JS can run. No hurry, let's keep looking down

ts-node

Let's take a look at the plug-in ts node, which can run directly ts file, and it will not be compiled js file.

npm i ts-node

// Run TS node index ts

At this point, we learned why TypeScript is used, its advantages and disadvantages, and how it works.

Then step into the ocean of basic knowledge of TypeScript ~, follow me.

Feel helpful small buddy can pay attention to: front end entertainment official account, thank you ~ ~ update a small skill every day.

7, Basic knowledge

1. Foundation static type

The basic type in TypeScript is the same as that in JavScript. It's just that some of them are new in Ts.

1. number

const count: number = 18; // Displays an annotation of type number

const count1 = 18; // If the annotation is not displayed, ts will automatically derive the type

2. string

const str: string = "Front end entertainment circle"; // Displays a string type for the annotation

const str1 = "Frogman"; // If the annotation is not displayed, ts will automatically derive the type

3. boolean

const status: string = false; // Displays a string type for the annotation

const status1 = true; // If the annotation is not displayed, ts will automatically derive the type

4. null

const value: null = null;

const value: null = undefined; // In this regard, the null type can be assigned undefined, which is the same as in js, null == undefined

5. undefined

const value: undefined = undefined;

const value: undefined = null; // In this regard, the null type can be assigned undefined, which is the same as in js, null == undefined

6. void

It is estimated that some small partners may be unfamiliar with void and think it is only available in TypeScript. In fact, it's not. The void keyword already exists in our JavaScript. It means invalid. Some friends may have seen < a href = "javascript: void (0)" > in earlier projects. This is the default behavior to control the jump of a tag. No matter how you execute the void method, it returns undefined

So what is the void type in our TypeScript. It also represents invalid. It is generally only used in functions to tell others that this function has no return value.

function fn(): void {} // correct

function testFn(): void {
    return 1; // An error is reported. The returned value is not accepted
}

function fn1(): void { return undefined} // It is also possible to display and return undefined types

function fn2(): void { return null} // It is also OK to display the returned null type, because null == undefined

7. never

Never is a type that will never have a value, or it can be said that it will never be completed. It means that it will not have a value. undefined and null are also regarded as values. Generally, this type will not be used or used. Just know this type.

const test: never = null; // error
const test1: never = undefined // error

function Person(): never { // Correct, because the loop is endless
    while(true) {}
}

function Person(): never { // Right, because recursion, there is never an exit
    Person()
}

function Person(): never { // The correct code reports an error and cannot be executed
    throw new Error()
}

8. any

Any this type represents any, any. I hope you don't define any type in the project. Although it works really well, it makes no sense for us to write TypeScript.

let value: any = ""; // correct
value = null // correct
value = {} // correct
value = undefined // correct

9. unknown

Unknown type is the second any type in our TypeScript, and it also accepts values of any type. Its English translation is unknown. Let's take a look at chestnuts

let value: unknown = ""	 
value = 1;
value = "fdsfs"
value = null
value = {}

There must be some friends wondering now. Well, it's unknown, which is equivalent to any type. What's the difference between the two. Let's take a look

let valueAny: any = "";
let valueUnknown: unknown = "";

valueAny = "Frogman";
valueUnknown = "Front end entertainment circle"

let status: null = false;
status = valueAny; // correct
status = valueUnknown // An error is reported. unknown type cannot be assigned to null type

Let's take a look at the above. Why can any type be assigned successfully, but unknown type can't? In the sense of the two, there is still a little difference. Any, arbitrary and unknown. So it doesn't matter if you assign any type to the unknown type, because it is an unknown type. But if you assign its unknown type to a null type, people will quit on the null side. I don't accept the unknown type.

To put it bluntly, others do not accept the unknown type, while the unknown type accepts others, ha ha ha.

2. Object static type

Speaking of object types, we can certainly think of objects including {}, arrays, classes and functions

1. object && {}

In fact, these two meanings are the same, {} and object represent non primitive types, that is, types other than number, string, boolean, symbol, null or undefined.

const list: object = {} // Empty object

const list1: object = null; // null object

const list: object = [] // Array object

const list: {} = {}
list.name = 1 // If an error is reported, the field inside cannot be changed, but it can be read
list.toString()

2. Array

const list: [] = []; // Define an array type

const list1: number[] = [1,2] // Define an array in which the value must be number

const list2: object[] = [null, {}, []] // Define an array that must be of object type

const list3: Array<number> = [1,2,3] // The generic definition array must be of type number, which we will talk about later

3. Class

// class
class ClassPerson = {
    name: "Front end entertainment circle"
}

const person: ClassPerson = new Person();
person.xxx = 123; // This line of code reports an error because the xxx attribute does not exist in the current class

4. Function

// function
const fn: () => string = () => "Front end entertainment circle" // Define that a variable must be of function type and the return value must be of string type

3. Function type annotation

Here, the function display annotation and function parameters will not cause type derivation problems.

1. The return type of the function is number

function fn(a, b): number {
    return a + b;
}
fn(1, 2)

2. Function void

The display annotation is of void type, and the function has no return value.

function fn(): void {
    console.log(1)
}

3. Function type derivation will not be performed automatically

You can see that the following function types will not be automatically derived. Although our arguments pass in 1 and 2, the formal parameters can accept any type value, so the system can't recognize what you pass, so we need to display and define the annotation type here.

function testFnQ(a, b) {
    return a + b
}
testFnQ(1,2)

Let's transform it.

function testFnQ(a:number, b:number) {
    return a + b
}
testFnQ(1,2)

Let's take another look at the annotation type displayed by the parameter object. You can assign each field type after the: sign.

function testFnQ(obj : {num: number}) {
    return obj.num
}
testFnQ({num: 18})

4. Tuple

Tuples are used to represent the number and type of a known array and define the type of each value in the array. They are generally not often used.

const arr: [string, number] = ["Front end entertainment circle", 1]

const arr: [string, string] = ["Front end entertainment circle", 1] // report errors

5. Enum enum

Enum enumeration type. The default value can be set. If it is not set, it is the index.

enum color {
    RED,
    BLUE = "blue",
    GREEN = "green"
}

// color["RED"] 0
// color["BLUE"] blue

If RED in the above color is not set, its value is 0. If BLUE is not set, its value is 1. They are incremented here. If a value is set, the set value is returned

Note that there is another problem here. Go directly to the code

Through the above study, we know that enum can be added value incrementally or set the default value. However, it should be noted that enum is not as flexible as json objects. Enum cannot set default values on any field.

For example, in the following chestnut, RED is not set, and then BLUE sets the default value, but GREEN is not set. At this time, the GREEN will report an error. Because you set the default value for the second BLUE and do not set it for the third, the code does not know how to increment, so an error is reported. Another solution is that you can set a numeric value for BLUE. At this time, the third GREEN will increase if it is not set, because it is of type number.

// report errors
enum color {
    RED,
    BLUE = "blue",
    GREEN
}

// good
enum color {
    RED,	   // 0
    BLUE = 4,  // 4
    GREEN      // 5
}

For example, enum enumeration types can also be contrasted. Check the key value through value. Like us, json objects do not support this writing method.

enum color {
    RED,	   // 0
    BLUE = 4,  // 4
    GREEN      // 5
}

console.log(color[4]) // BLUE
console.log(color[0]) // RED

5. Interface

What is the interface? The interface is convenient for us to define one code and reuse multiple codes. There are also some modifiers in the interface. Now let's meet them.

1. How to reuse interfaces

For example, before we talk about this, we don't know the interface. If you may need to define a type for the object, you may do so.

const testObj: { name: string, age: number } = { name: "Front end entertainment circle", age: 18 }

const testObj1: { name: string, age: number } = { name: "Frogman", age: 18 }

Let's use the interface to transform it.

interface Types {
    name: string, 
    age: number
}

const testObj: Types = { name: "Front end entertainment circle", age: 18 }

const testObj1: Types = { name: "Frogman", age: 18 }

You can see that the interface keyword is used to define an interface, and then assigned to these two variables to realize reuse.

2. readonly modifier

readonly type, which can only read the status and cannot be changed.

interface Types {
    readonly name: string, 
    readonly age: number
}

const testObj: Types = { name: "Front end entertainment circle", age: 18 }

const testObj1: Types = { name: "Frogman", age: 18 }

testObj.name = "Zhang San" // The name property cannot be changed because it is read-only
testObj1.name = "Li Si" // The name property cannot be changed because it is read-only

3. ? Optional modifier

Optional modifiers to? Definition, why do we need optional modifiers? Because if we don't write optional modifiers, the properties in the interface are required.

interface Types {
    readonly name: string, 
    readonly age: number,
    sex?: string
}

const testObj: Types = { name: "Front end entertainment circle", age: 18}

4. Extensions inheritance

Our interface can also be inherited. Like the ES6Class class, we use the extends keyword.

interface Types {
    readonly name: string, 
    readonly age: number,
    sex?: string
}

interface ChildrenType extends Types { // The ChildrenType interface already inherits the parent Types interface
    hobby: []
}
    
const testObj: ChildrenType = { name: "Front end entertainment circle", age: 18, hobby: ["code", "badminton"] }

5. propName extension

This function in the interface is very powerful. It can write properties that are not in the interface.

interface Types {
    readonly name: string, 
    readonly age: number,
    sex?: string,
}

const testObj: Types = { name: "Front end entertainment circle", age: 19, hobby: [] } 

The above line of testObj will be popular because the hobby attribute does not exist in the interface interface, so we won't let others write it in the interface we don't exist?. At this time, you can customize the propName above.

interface Types {
    readonly name: string, 
    readonly age: number,
    sex?: string,
    [propName: string]: any // propName field must be of type string or number. The value is of type any, that is, arbitrary
}

const testObj: Types = { name: "Front end entertainment circle", age: 19, hobby: [] } 

When you run the above code, you can see that it is not red~

6. Type

Let's take another look at Type, which is made by declaring Type alias. Alias types can only be defined as: basic static Type, object static Type, tuple and union Type.

Note: the type alias cannot define an interface

type Types = string;

type TypeUnite = string | number

const name: typeUnite = "Front end entertainment circle"
const age: typeUnite = 18

1. What is the difference between type alias and interface interface

1. type does not support interface declaration
type Types = number
type Types = string // An error is reported. Duplicate names are not allowed for the type alias type

interface Types1 {
    name: string
}

interface Types1 {
    age: number
}

// The interface interface can have duplicate type names. If they occur repeatedly, they will be merged into {name: string, age: number}

The alias type of the first Types type does not allow duplicate names. The interface interface can have duplicate type names. If they occur repeatedly, they are merged, that is, they become {name: string, age: number}

Let's take another look at the interface

interface Types1 {
    name: string
}

interface Types1 {
    name: number
}

You can see the above two interface interfaces with the same name. The properties in them are also the same name, but the types are different. Types1 of the second one will pop up red, indicating that the interface declared later must be consistent with the attribute type of the same name declared earlier. Replace the name and its type declared later with string.

2. type expression not supported by interface
const count: number = 123
type testType = typeof count

const count: number = 123

interface testType {
    [name: typeof count]: any // report errors
}

You can see that the above type supports expressions, but the interface does not

3. type supports type mapping, but interface does not
type keys = "name" | "age"  
type KeysObj = {
    [propName in keys]: string
}

const PersonObj: KeysObj = { // normal operation
    name: "Frogman",
    age: "18"
} 

interface testType {
    [propName in keys]: string // report errors
}

7. Joint type

The union type is represented by | which means that one of the types can be satisfied.

const statusTest: string | number = "Front end entertainment circle"

const flag: boolean | number = true

Take another look at chestnuts. Let's use union types with function parameters to see what happens

function testStatusFn(params: number | string) {
    console.log(params.toFixed()) // report errors
}

testStatusFn(1)

As we mentioned above, function parameter types cannot be automatically derived. Moreover, the system is more confused when using joint types, and the type of current arguments cannot be recognized. Therefore, an error is reported when accessing the method on the current type.

Next, I'll show you some type protection. It sounds very advanced. In fact, we've all seen these. Don't forget to remember: front end entertainment, official account, oh hee hee.

1. typeof

function testStatusFn(params: number | string) {
    console.log(params.toFixed()) // report errors
}
testStatusFn(1)

After transformation

// normal
function testStatusFn(params: string | number) {
    if (typeof params == "string") {
        console.log(params.split)
    }

    if (typeof params == "number") {
        console.log(params.toFixed)
    }
}

testStatusFn(1)

2. in

// report errors
interface frontEnd {
    name: string
}

interface backEnd {
    age: string
}

function testStatusFn(params: frontEnd | backEnd) {
    console.log(params.name)
}

testStatusFn({name: "Frogman"})

After transformation

// normal
function testStatusFn(params: frontEnd | backEnd) {
    if ("name" in params) {
        console.log(params.name)
    }

    if ("age" in params) {
        console.log(params.age)
    }
}

testStatusFn({name: "Frogman"})

3. as assertion

// report errors
interface frontEnd {
    name: string
}

interface backEnd {
    age: string
}

function testStatusFn(params: frontEnd | backEnd) {
    console.log(params.name)
}

testStatusFn({name: "Frogman"})

After transformation

// normal
function testStatusFn(params: frontEnd | backEnd) {
    if ("name" in params) {
        const res = (params as frontEnd).name
        console.log(res)
    }
    
    
    if ("age" in params) {
        const res = (params as backEnd).age
        console.log(res)
    }
}

testStatusFn({age: 118})

8. Cross type

Cross type is the opposite of union type. It is represented by &. Cross type is that two types must exist. Here also use the above combined type chestnuts.

interface frontEnd {
    name: string
}

interface backEnd {
    age: number
}

function testStatusFn(params: frontEnd & backEnd) {}

testStatusFn({age: 118, name: "Front end entertainment circle"})

Here we can see that the argument must pass in all attribute values of two * * interfaces * *. The union type is the type passed in.

Note: an attribute with the same name appears on our interface

interface frontEnd {
    name: string
}

interface backEnd {
    name: number
}

function testStatusFn(params: frontEnd & backEnd) {
    console.log(params)
}

testStatusFn({name: "front end"})

The properties with the same name appear in the above two interface types, but the types are different. At this time, the type will become never.

9. Generics

Generics are the most difficult to understand in TypeScript. Here I try to explain them in an easy to understand way.

function test(a: string | number, b: string | number) {
    console.log(a, b)
}
test(1, "Front end entertainment circle")

For example, in the above chestnut, the function parameter annotation type defines string and number. There is no problem in calling the function argument, but there is a requirement, It is the argument. We must pass in the same type (pass in two number types). Although the above joint type can also be implemented, if we want to add a boolean type, the joint type must also add a boolean, which is too redundant.

At this time, you need to use generics. Generics are specifically used for uncertain types and are flexible. Generics are mostly used with < T >, of course, they can also be used casually, such as < test >, < custom >.

function test<T>(a: T, b: T) {
    console.log(a, b)
}
test<number>(1, "Front end entertainment circle") // The call is followed by angle brackets, which is the type of generic type. At this time, an error is reported. Because the type used in the call is number, you can only pass in the same type

test<boolean>(true, false) 

test<string>("Front end entertainment circle", "Frogman")

The above use of generics solves the problem of passing in the same type parameter, but generics can also use different parameters, and the call type can be defined as < any >

function test<T>(a: T, b: T) {
    console.log(a, b)
}

test<any>(1, "Front end entertainment circle")

But there is another problem with the above one. It can pass in objects, but if we only want to pass in number and string types. Then our generics also provide us with * * constraint types. Generic types use extensions for type constraints * *. Only string and number types can be selected.

function test<T extends number | string, Y extends number | string>(a: T, b: Y) {
    console.log(a, b)
}

test<number, string>(18, "Front end entertainment circle")

test<string, number>("Front end entertainment circle", 18)

In this case, the generic type is passed in, separated by commas, to define what each type wants to be. Remember that generics can only be used for types we are not sure about.

10. Module

TypeScript also supports import and export, which is known to most of the partners here. I won't talk about it here.

// Import

import xxx, { xxx } from "./xxx"

// export

export default {}

export const name = "Front end entertainment circle"

If you don't understand, you can read my previous articles Talk about CommonJs and Es Module and their differences

11. Class

The following three modifiers can only be used in TypeScript classes and are not supported in JavaScript classes.

1. public

Public is the public attribute of a class, that is, you can access the attributes and methods in the class whether inside or outside the class. The default defined properties and methods are public.

class Person {
	name = "Front end entertainment circle";
	public age = 18;
}
const res = new Person();
console.log(res.name, res.age) // Front entertainment circle 18

As can be seen above, the print results can be displayed. The name attribute does not define the public attribute, so the attributes and methods defined in the class are all public by default.

2. private

Private is the private attribute of the class. It can only be accessed in the current class. The current class is in the {} inner area. Properties and methods defined by private cannot be accessed outside {}

class Person {
	private name = "Front end entertainment circle";
	private age = 18;
}
const res = new Person();
console.log(res.name, res.age) // These two lines will be popular. The current property is private and can only be accessed inside the class

class Scholl extends Person {
    getData() {
        return this.username + "," + this.age
    }
}
const temp = new Scholl()
console.log(temp.getData()) // Red ~, although it inherits the Person class, the private definition can only be accessed in the current class, and subclasses cannot be accessed.

3. protected

Protected is the protection attribute of the class, which can be accessed only in the current class and subclasses. That is, subclasses defined with the protected attribute can also be accessed.

class Person {
    protected username = "Front end entertainment circle";
    protected age = 18;
}
const res = new Person();
console.log(res.name, res.age) // These two lines will be popular. The current property is private and can only be accessed inside the class

class Scholl extends Person {
    getData() {
        return this.username + "," + this.age
    }
}
const temp = new Scholl()
console.log(temp.getData()) // Front end entertainment, 18. The properties of the parent class can be accessed normally

4. implements

The implements keyword can only be used in a class. As its name implies, it implements a new class and implements all properties and methods from the parent or from the interface. If the existing properties and methods in the interface are not written in the PersonAll class, an error will be reported.

interface frontEnd {
    name: string,
    fn: () => void
}

class PersonAll implements frontEnd {
    name: "Front end entertainment circle";
    
    fn() {
        
    }
}

5. Abstract class

Abstract classes are defined using the abstract keyword. Abstract abstract abstract methods cannot be instantiated. If a method in an abstract class is abstract, its own class must also be abstract. Abstract methods cannot write function bodies. If there is an abstract method in the parent class, the child class must also rewrite the method.

// abstract class
abstract class Boss {
    name = "Qin Dynasty";
    call() {} // Abstract methods cannot write function bodies
}

class A extends Boss {
    call() {
        console.log(this.name);
        console.log("A")
    }
}

class B extends Boss {
    call() {
         console.log("B")
    }
}

new A().call()

The usage scenario of this abstract class, such as A requirement or B requirement, just needs A public attribute, and then it has some own logic. You can use the abstract class, which can only be used in TypeScript.

12. namespace

We learned that we can see now. I don't know if the partners found that there can be no duplicate variables in the project file (whether you are the same file or other files), otherwise it will be popular directly. One of the most explicit purposes of namespaces is to solve the problem of duplicate names.

Namespaces are defined using the namespace keyword. Let's look at chestnuts.

index.ts

namespace SomeNameSpaceName { 
    const q = {}

    export interface obj {
        name: string
    }
}

In this way, a namespace is defined. You can see that the variable q does not write the export keyword, which proves that it is an internal variable, even if it is other variables The ts file references it, and it will not be exposed. The obj interface can be accessed globally.

We access the current namespace on another page

1. reference Introduction

/// <reference path="./index.ts" />
namespace SomeNameSpaceName { 
	export class person implements obj {
		name: "Front end entertainment circle"
	}
}

2. import

export interface valueData {
     name: string
}
import { valueData } from "./xxx.ts"

At this time, after using the namespace, the problem of red explosion of duplicate names of different files can be solved.

13. tsConfig.json

This tsconfig file is how we compile the ts file and how to compile the ts file into our js file. tsc -init this command will generate this file. After executing this command, we can see that a tsconfig. Config will be generated in the root directory JSON file, which has a bunch of attributes.

So how do we compile ts files into js files? Directly execute the tsc command to compile all files in the root directory ts files are compiled into js file output to the project.

For more configuration documents, refer to Official website

{
    // include: ["*.ts"] / / convert all ts files in the directory into js files
    // Include: [index.ts] / / only index.ts under the item Convert TS file to js file
    // files: ["index.ts"] / / like include, only the files in the current array value are executed. The current files must write the relative path
    // Exclude: [index.ts] / / exclude is the exception to index TS does not execute, all others execute
    
    compilerOptions: {
        removeComments: true, // Remove the comments from the compiled js file
        outDir: "./build", // js file directory for final output
        rootDir: "./src", // ts entry file lookup
    }
}

8, Utility type

Finally, let's talk about utility types. The TypeScript standard library comes with some utility types. These utility classes are convenient interfaces. Here are just a few common and more practical types Official website

1. Exclude

Exclude another type from one type, which can only be a union type, and exclude the UtilityLast type from the TypesTest type.

For: Union type

interface UtilityFirst {
    name: string
}

interface UtilityLast {
    age: number
}

type TypesTest = UtilityFirst | UtilityLast;

const ObjJson: Exclude<TypesTest, UtilityLast> = {
    name: "Front end entertainment circle"
}

2. Extract

Extract is just the opposite of the above one. This is to select an assignable union type and only select the UtilityLast type from the TypesTest type.

For: Union type

interface UtilityFirst {
    name: string
}

interface UtilityLast {
    age: number
}

type TypesTest = UtilityFirst | UtilityLast;

const ObjJson: Extract<TypesTest, UtilityLast> = {
    age: 1
}

3. Readonly

Converts all property values of an array or object to read-only. Here is just a demonstration of the same way to write object chestnuts and arrays.

Applicable to: objects, arrays

interface UtilityFirst {
    name: string
}

const ObjJson: Readonly<UtilityFirst> = {
    name: "Front end entertainment circle"
}
ObjJson.name = "Frogman" // Error reporting read-only status

4. Partial

Set all properties of the object to optional. We know that as long as the interface is not set? Modifier, then all objects are required. This utility class can convert all properties to optional.

For: objects

interface UtilityFirst {
    name: string
}

const ObjJson: Partial<UtilityFirst> = {
    
}

5. Pick

Pick select some key values in the object type and extract them. The first parameter is the target value, and the second parameter is the joint key

For: objects

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

const ObjJson: Pick<UtilityFirst, "name" | "age"> = {
    name: "Front end entertainment circle",
    age: 18
}

6. Omit

Omit selects some key values in the object type and filters them out. The first parameter is the target value, and the second parameter is the joint key

For: objects

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

const ObjJson: Omit<UtilityFirst, "name" | "age"> = {
    hobby: ["code", "badminton"]
}

7. Required

Required converts all optional attributes of the object to required attributes.

For: objects

interface UtilityFirst {
    name?: string,
    age?: number,
    hobby?: string[]
}

const ObjJson: Required<UtilityFirst> = {
    name: "Frogman",
    age: 18,
    hobby: ["code"]
}

8. Record

Create an object result set. The first parameter is the key value and the second parameter is the value value. It stipulates that we can only create field values in this field.

For: objects

type IndexList = 0 | 1 | 2

const ObjJson: Record<IndexList, "Front end entertainment circle"> = {
    0: "Front end entertainment circle",
    1: "Front end entertainment circle",
    2: "Front end entertainment circle"
}

9, Gossip

Let's remind the partners who rent a house in Tongzhou, Beijing. Recently, they have been cheated by the dog B real estate company. They deliberately don't refund the deposit when the house is due. Pay attention to the partners looking for a house in Tongzhou. Don't meet this dog intermediary company. This company registers a bunch of company names, such as Beijing Junqi real estate and Beijing Junye real estate, which deliberately deceive people under the banner of the 21st century. You must ask me why I find such a small company to rent a house. Tama's here also needs to make complaints about this App. I first used this App to rent a house, but I didn't think it was a bunch of small intermediary companies like this. It was really disgusting. You have to find a big company to rent a house. It's reliable and reassuring.

thank

Thank you for reading this article. I hope it can help you. If you have any questions, you are welcome to correct them.
I'm a frog man. If you think it's OK, please praise it
Interested partners can join [front-end entertainment communication group] and welcome to communicate and discuss together
Writing is not easy, "like" + "watching" + "forwarding". Thank you for your support
The next update TypeScript actual combat, welcome to pay attention

reference material

Keywords: Front-end TypeScript

Added by Cerberus_26 on Mon, 20 Dec 2021 11:20:23 +0200