This is the 25th day of my participation in the August Genwen Challenge.More challenges in August


Why TypeScript

TypeScript allows us to avoid errors in our development of types or code results that are not what we expected. XXX is not defined We all know that JavaScript errors are thrown at runtime, but TypeScript errors are reported to us directly in the editor, which greatly improves development efficiency and eliminates the need to spend a lot of time writing single tests and troubleshooting bugs.

Pros and cons of TypeScript

advantages

  • In general, we need to look at the field type on the interface document when we perform front-end and back-end tuningTypeScriptIt will automatically help us identify the current type. Saves us going to seeThe documentornetworkTime. This is called type derivation (we’ll get to that in a second)
  • Kindly prompt errors in the editor to prevent code from being corrupted by implicit conversions at runtime.

disadvantages

  • There are certain learning costs,TypeScriptThere are several types of concepts,Interface interface,Class class,Enum enumeration,Generics genericIt takes time for us to learn.
  • It may not work perfectly with some of the plug-in libraries

TypeScript processes and JavaScript code processes

1. The running process of JavaScript is as follows, depending on the NodeJs environment and browser environment

  • willJavaScriptCode conversion toJavaScript-AST
  • willASTCode is converted to bytecode
  • Computes bytecode during operation

2. TypeScript runs the process. The following operations are TSC operations

  • willTypeScriptThe code compiles toTypeScript-AST
  • checkASTType checking on code
  • After type checking, compile toJavaScriptcode
  • JavaScriptCode conversion toJavaScript-AST
  • willASTCode is converted to bytecode
  • Computes bytecode during operation

Differences between TypeScript and JavaScript

Only by understanding the difference can we understand TypeScript better

Type System features JavaScript TypeScript
How are types bound? dynamic static
Is there any type implicit conversion? is no
When to check the type? The runtime Compile time
When to report an error The runtime Compile time

1. Type conversion

JavaScript

For example, in a code snippet like 1 + true in JavaScript, JavaScript has an implicit conversion where true becomes number and number(true) is added to 1.

TypeScript

In TypeScript, code such as 1+true raises an error in TypeScript indicating that the number type cannot operate with the Boolean type.

2. When to check the type

JavaScript

In JavaScript you can only check the type while the program is running. There will also be implicit conversions of types, which can be tricky.

TypeScript

In TypeScript, types are checked at compile time, and if they don’t match the expected type, an error will be reported and the editor will explode

3. When to report an error

JavaScript

In JavaScript, exceptions can only be thrown when the program is executing. JavaScript has implicit conversions, so when the program is executing, we really know whether the code type is the expected type or whether the code is valid.

TypeScript

In TypeScript, when you write code in the editor, an exception is thrown directly, which is very efficient and convenient.

TypeScript’s two modes

1. Explicit annotation types

Take a chestnut

let name: string = "Front-end Gold Digger.";

let age: number = 38;

let hobby: string[] = ["write code"."Play the game"]
Copy the code

An explicit annotation type is a type defined when a variable is declared, so we can see that the name is a string.

2. Derivation types

Take a chestnut

let name = "Front-end Gold Digger."// Is a string

let age = 38;  // Is a number type

let hobby = ["write code"."Play the game"// Is a string array type
Copy the code

To derive a type is to remove the display annotation, and the system automatically identifies what type the current value is.

Install TypeScript && to run

typescript

Install the typescript environment globally.

npm i -g typescript
Copy the code

How do we run.ts files when typescript is installed? We can run TSC after typescript is installed.

TSC index.ts: TSC index.ts: TSC index.ts: TSC index.ts: TSC index.ts You can then see that an index.js is compiled under the directory, which is the result of TSC compilation.

index.ts

const userName: string = "Front-end Gold Digger." 
Copy the code

When you run TSC index.ts, you can see that a new index.js file is generated at the level of the TSC index.ts file.

var userName = "Front-end Gold Digger."
Copy the code

If you run the TSC command, you can compile a file. If you run the TSC command, you can compile a file. If you run the TSC command, you can compile a file. No hurry. Let’s move on

ts-node

Take a look at the plugin ts-Node, which can run the.ts file directly without compiling the.js file.

npm i ts-node

// Run ts-node index.ts
Copy the code

At this point we’ve seen why we use TypeScript, its pros and cons, and how it works.

Now comes the basics of TypeScript

7. Basic knowledge

1. Basic static types

Base types in TypeScript are the same as our base types in JavScript. It’s just that they’re new to Ts.

1. number

const count: number = 18// display annotation of a number type

const count1 = 18// Do not display annotations, ts will automatically deduce the type
Copy the code

2. string

const str: string = "Front-end Gold Digger."// Display annotation of a string type

const str1 = "Frogman"// Do not display annotations, ts will automatically deduce the type
Copy the code

3. boolean

const status: string = false// Display annotation of a string type

const status1 = true// Do not display annotations, ts will automatically deduce the type
Copy the code

4. null

const value: null = null;

const value: null = undefined// The null type can be assigned undefined as in JS, null == undefined
Copy the code

5. undefined

const value: undefined = undefined;

const value: undefined = null// The null type can be assigned undefined as in JS, null == undefined
Copy the code

6. void

For those of you who are unfamiliar with void, we assume that void is only available in TypeScript. No matter what you do with void it returns undefined, okay

So what is void in TypeScript? It also means invalid and is usually used on a function to tell someone that the function does not return a value.

function fn() :void {} / / right

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

function fn1() :void return undefined// display returns undefined, which is also ok

function fn2() :void return null// Display return null type is also ok, because null == undefined
Copy the code

7. never

Never A type that never has a value or a type that never executes. Undefined and null are also values. Normally this type is not used and is not used. You know the 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 // Correct, there is never an exit because of recursion
    Person()
}

function Person() :never // There is an error in the correct code
    throw new Error()}Copy the code

8. any

The type any stands for any and arbitrary. I don’t want you to define an any type in your project. While it does work, it makes no sense for us to write TypeScript.

let value: any = ""/ / right
value = null / / right
value = {} / / right
value = undefined / / right
Copy the code

9. unknown

The unknown type is the second any type in TypeScript that 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 = {}
Copy the code

What is the difference between unknown and any? Let’s see

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

valueAny = "Frogman";
valueUnknown = "Front-end Gold Digger."

let status: null = false;
status = valueAny; / / right
status = valueUnknown // Error: cannot assign unknown type to null type
Copy the code

The value of any can be assigned successfully and that of unknown cannot be assigned successfully. So it doesn’t matter if you assign any type to unknown because it’s already an unknown type. However, if you assign a null type to its unknown type, then the null side will not accept unknown type.

To put it bluntly, unknown types do not accept others, and unknown types accept others, hahaha.

2. Static type of the object

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

1. object && {}

{} object is a primitive type except number, string, Boolean, symbol, null or undefined.

const list: object = {} / / null objects

const list1: object = null/ / null objects

const list: object = [] // Array object

const list: {} = {}
list.name = 1 // The error cannot be changed, but can be read
list.toString()
Copy the code

An array of 2.

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

const list1: number[] = [1.2// Define an array with a literal value of number

const list2: object[] = [null, {}, []] // Define an array that must contain object types

const list3: Array<number> = [1.2.3// Generics define that the array must be of type number. Generics will be covered later
Copy the code

Class 3.

/ / class
class ClassPerson = {
    name"Front-end Gold Digger."
}

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

4. The function

/ / function
const fn: () = > string = () = > "Front-end Gold Digger." // Define that a variable must be of function type and the return value must be string
Copy the code

3. Function type annotations

Function display annotations and function arguments are not type inferred.

1. The function return type is number

function fn(a, b) :number {
    return a + b;
}
fn(1.2)
Copy the code

2. The function is void

Displays the annotation as void and the function returns no value.

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

3. Functions do not automatically type derive

As you can see in the following function types, there is no automatic type derivation. We pass 1 and 2 arguments, but the parameter aspect can accept any type value, so the system can’t recognize what you passed, so we need to display the definition annotation type here.

function testFnQ(a, b{
    return a + b
}
testFnQ(1.2)
Copy the code

Screenshot of wechat _20210824233905.png

Let’s reinvent it.

function testFnQ(a:number, b:number{
    return a + b
}
testFnQ(1.2)
Copy the code

Let’s look at the parameter object display annotation type, also after the: sign to assign each field type.

function testFnQ(obj : {num: number}{
    return obj.num
}
testFnQ({num18})
Copy the code

4. A Tuple Tuple

Tuples are used to represent an array of known numbers and types, defining the type of each value in the array, and are not often used.

const arr: [string, number] = ["Front-end Gold Digger.".1]

const arr: [string, string] = ["Front-end Gold Digger.".1/ / an error
Copy the code

5. Enumeration Enum

Enum Enum type. The default value can be set. If no value is set, the value is index.

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

// color["RED"] 0
// color["BLUE"] blue
Copy the code

Like the color above, RED has no value and its value is 0, and BLUE has no value and its value is 1. They are incremented here. If set, returns the set value

Notice there’s another problem here, so let’s go straight to the code

Enum can be incremented or set to a default value. It is important to note, however, that enums are not as flexible as JSON objects. Enums cannot set default values on arbitrary fields.

For example, if RED is not set, then BLUE is set to default, but GREEN is not set, then the GREEN will report an error. Because you set the default value for the second BLUE, and do not set the default value for the third BLUE, then the code does not know how to increment, so the error is reported. Alternatively, you can assign a number to BLUE, and the third GREEN will increment without setting it, because it is of type number.

/ / an error
enum color {
    RED,
    BLUE = "blue",
    GREEN
}

// good
enum color {
    RED,    / / 0
    BLUE = 4./ / 4
    GREEN      / / 5
}
Copy the code

For example, enum enum types can also be contrasted. You can use value to check key values. Json objects like ours do not support this notation.

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

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

5. The Interface Interface

What is an interface? An interface is just a way to define one piece of code and reuse it. There are also modifiers in interfaces. Let’s get to know them.

1. How to reuse interfaces

For example, before we got to this point, if we didn’t know about interfaces, we might want to define a type for an object, you might want to do that.

const testObj: { name: string, age: number } = { name"Front-end Gold Digger.".age18 }

const testObj1: { name: string, age: number } = { name"Frogman".age18 }
Copy the code

Let’s change it up with interfaces.

interface Types {
    name: string, 
    age: number
}

const testObj: Types = { name"Front-end Gold Digger.".age18 }

const testObj1: Types = { name"Frogman".age18 }
Copy the code

You can see that you use the interface keyword to define an interface and then assign it to both variables for reuse.

2. Readonly modifier

The value is of the readonly type and cannot be changed.

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

const testObj: Types = { name"Front-end Gold Digger.".age18 }

const testObj1: Types = { name"Frogman".age18 }

testObj.name = "Zhang" // Cannot change the name attribute because it is read-only
testObj1.name = "Bill" // Cannot change the name attribute because it is read-only
Copy the code

3.? Optional modifier

Optional modifiers start with? Definition, why do we need optional modifiers, because if we don’t write optional modifiers, then all the properties in the interface are mandatory.

interface Types { readonly name: string, readonly age: number, sex? : string }const testObj: Types = { name"Front-end Gold Digger.".age18}
Copy the code

4. Extends to inherit

Our interface is also inheritable, using the extends keyword just like the ES6Class class.

interface Types { readonly name: string, readonly age: number, sex? : string } interface ChildrenTypeextends Types { 
    The ChildrenType interface already inherits the parent Types interface
    hobby: []}const testObj: ChildrenType = { 
    name"Front-end Gold Digger.".age18.hobby: ["code"."Badminton"]}Copy the code

5. PropName extension

Interface is a very powerful way to write properties that aren’t in the interface.

interface Types { readonly name: string, readonly age: number, sex? : string, }const testObj: Types = { name"Front-end Gold Digger.".age19.hobby: []}Copy the code

TestObj = testObj; testObj = testObj; testObj = testObj; testObj = testObj; testObj = testObj . You can use custom 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, which is arbitrary
}

const testObj: Types = { name"Front-end Gold Digger.".age19.hobby: []}Copy the code

Run the above code, you can see that the red does not explode ~

6. Type

Alias types can only be defined as: base static Type, object static Type, tuple, union Type.

Note: The type alias cannot define an interface

type Types = string;

type TypeUnite = string | number

const name: typeUnite = "Front-end Gold Digger."
const age: typeUnite = 18
Copy the code

1. What is the difference between type alias and interface

1. Type does not support the interface declaration
type Types = number
type Types = string // An error has been reported. The type alias type does not allow duplicate names

interface Types1 {
    name: string
}

interface Types1 {
    age: number
}

{name: string, age: number}} {age: number}
Copy the code

{name: string, age: number}} {name: string, age: number}}

Let’s do another case of interface

interface Types1 {
    name: string
}

interface Types1 {
    name: number
}
Copy the code

You can see the above two interfaces with the same name, and the properties in them are also the same name, but of different types. The second Types1 will explode, telling you that the interface declared later must be the same as the property of the same name declared earlier. Replace the name declared later with a string.

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

const count: number = 123

interface testType {
    [name: typeof count]: any / / an error
}
Copy the code

As you can see above, type supports expressions, while 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 = { // It is running properly
    name"Frogman".age"18"
} 

interface testType {
    [propName in keys]: string / / an error
}
Copy the code

7. Union types

, ie, the joint types with | said can satisfy one of the type.

const statusTest: string | number = "Front-end Gold Digger."

const flag: boolean | number = true
Copy the code

Let’s look at chestnuts. Let’s use the union type with the function argument and see what happens

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

testStatusFn(1)
Copy the code

As mentioned above, function parameter types cannot be typed automatically, especially now that combined types are used, the system is even more confused and cannot recognize the type of the current argument. So accessing a method on the current type is an error.

I’m going to show you some types of protection, which sounds pretty advanced, but you’ve all seen it before.

1. typeof

function testStatusFn(params: number | string{
    console.log(params.toFixed()) / / an error
}
testStatusFn(1)
Copy the code

After transforming

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

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

testStatusFn(1)
Copy the code

2. in

/ / an error
interface frontEnd {
    name: string
}

interface backEnd {
    age: string
}

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

testStatusFn({name"Frogman"})
Copy the code

After transforming

/ / 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"})
Copy the code

3. As assertions

/ / an error
interface frontEnd {
    name: string
}

interface backEnd {
    age: string
}

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

testStatusFn({name"Frogman"})
Copy the code

After transforming

/ / 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({age118})
Copy the code

8. Cross types

A cross type, as opposed to a union type, is represented by an ampersand. A cross type means that both types must exist. Let’s also use the union type chestnuts above.

interface frontEnd {
    name: string
}

interface backEnd {
    age: number
}

function testStatusFn(params: frontEnd & backEnd{}

testStatusFn({age118.name"Front-end Gold Digger."})
Copy the code

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

Note: Our interface appears with a property of the same name

interface frontEnd {
    name: string
}

interface backEnd {
    name: number
}

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

testStatusFn({name"Front end"})
Copy the code

The same attribute appears in both interface types, but of different types, so the type changes to never.

9. The generic

Generics are one of the hardest things in TypeScript to understand, so I’ll try to make it as simple as possible.

function test(a: string | number, b: string | number{
    console.log(a, b)
}
test(1."Front-end Gold Digger.")
Copy the code

For example, the function argument annotation type defines string and number. There is no problem with calling the function argument, but there is a requirement that the argument must be passed the same type. Although the above union type can be implemented, if we want to add a Boolean, then the union type must also append a Boolean, which would be too redundant.

This is where generics come in. Generics are designed for use with uncertain types and are flexible. Most of the use of generic type is the use of

, of course, can also be used freely, such as:

,

can be.


function test<T> (a: T, b: T{
    console.log(a, b)
}
test<number>(1."Front-end Gold Digger."// This is the type of the generic type. This is an error, because the type used in the call is number

test<boolean>(true.false) 

test<string>("Front-end Gold Digger."."Frogman")
Copy the code

This uses generics to solve the problem of passing the same type argument, but generics can also use different arguments. You can define the call type as

.

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

test<any>(1."Front-end Gold Digger.")
Copy the code

But there’s another problem with this one, it can pass in objects, but if we just want to pass in numbers and strings. So our generics also give us ** constraint types. Generics use extends to restrict ** to string and number.

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

test<number, string>(18."Front-end Gold Digger.")

test<string, number>("Front-end Gold Digger.".18)
Copy the code

At this point, when you pass in a generic type, you use comma separation to define what each type wants to be. Remember, we can only use generics for types we are not sure about.

10. The module

TypeScript also supports import and export. Most of you know that, but I won’t go into that here.

/ / import

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

/ / export

export default {}

export const name = "Front-end Gold Digger."
Copy the code

If you don’t understand, please read my previous articles to talk about CommonJs and Es Module and the difference between them [1]

11. The Class Class

These three modifiers are only available in TypeScript classes and are not supported in JavaScript classes.

An error. The PNG

1. public

Public is the public attribute of a class, which means that the attributes and methods in the class can be accessed either inside or outside the class. Properties and methods defined by default are public.

class Person {
 name = "Front-end Gold Digger.";
 public age = 18;
}
const res = new Person();
console.log(res.name, res.age) // Front-end Nuggets 18
Copy the code

The name property does not define a public public property, so all properties and methods defined in the class are defined as public by default.

2. private

Private is the private property of a class and can only be accessed in the current class, which is the field inside {}. Properties and methods defined by private are not accessible outside {}

class Person {
 private name = "Front-end Gold Digger.";
 private age = 18;
}
const res = new Person();
console.log(res.name, res.age) 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()) The Person class is inherited, but the private definition is only accessible by the current class and not by subclasses.
Copy the code

3. protected

Protected is the protected property of a class. Only the current class and subclasses can access it. This means that subclasses defined with the protected property can also be accessed.

class Person {
    protected username = "Front-end Gold Digger.";
    protected age = 18;
}
const res = new Person();
console.log(res.name, res.age) 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 Nuggets, 18. Properties of the parent class can be accessed normally
Copy the code

4. implements

The implements keyword can only be used in a class, which, as the name implies, implements a new class that implements all properties and methods from the parent or interface. An error is reported if the PersonAll class does not include properties and methods already in the interface.

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

class PersonAll implements frontEnd {
    name"Front-end Gold Digger.";
    
    fn(){}}Copy the code

5. An abstract class

Abstract classes are defined using the abstract keyword. Abstract methods cannot be instantiated. If the methods in an abstract class are abstract, then the class itself must also be abstract. Abstract methods cannot write function bodies. If there is an abstract method in the parent class, the subclass must redo that method.

/ / abstract classes
abstract class Boss {
    name = "Qin";
    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()
Copy the code

The abstract class uses scenarios such as A requirement or B requirement that needs A common property, and then some logic of its own, to use abstract classes, which are only available in TypeScript.

12. Namespace namespace

We learned that we can now see, if you haven’t noticed, that files in projects can’t have duplicate variables (whether you’re the same file or not), or they’ll go viral. One of the most explicit purposes of namespaces is to solve the duplication problem.

Namespaces are defined using the namespace keyword.

index.ts

namespace SomeNameSpaceName { 
    const q = {}

    export interface obj {
        name: string
    }
}
Copy the code

As you can see, the variable q does not have the export keyword, which proves that it is an internal variable and will not be exposed even if other.ts files refer to it. The obJ interface is globally accessible.

We access the current namespace on another page

1. Introduced the reference

/// <reference path="./index.ts" />
namespace SomeNameSpaceName { 
 export class person implements obj {
  name"Front-end Gold Digger."}}Copy the code

2. import

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

At this time, after using the namespace can completely solve the problem of different files with the same name.

13. tsConfig.json

This tsconfig file is how we compile TS files and how to compile ts files into our JS files. The tsc-init command will generate the file. After executing this command, we can see that a tsconfig.json file with a bunch of properties is generated in the root directory.

Ts files in the root directory can be compiled into.js files directly by executing TSC command.

For more configuration documents, please refer to the official website [2]

{
    // include: ["*.ts"] // Convert all ts files in the directory to js files
    // include: ["index.ts"] // Convert only index.ts files under the project to js files
    // files: ["index.ts"] // Like include, only files in the current array value are executed. The current files must be written in relative paths
    // exclude: ["index.ts"] // exclude: ["index.ts"] // exclude: ["index.ts"
    
    compilerOptions: {
        removeCommentstrue.// Remove comments from compiled js files
        outDir"./build".// The final output js file directory
        rootDir"./src".// ts entry file lookup}}Copy the code

Eight, practical type

Finally, some utility types come with the TypeScript standard library. These utility classes are all convenient interfaces. Here are just a few common, more useful types. [3]

1. Exclude

Exclude one type from another, only union types, and exclude UtilityLast types from TypesTest types.

Applicable to: Union type

interface UtilityFirst {
    name: string
}

interface UtilityLast {
    age: number
}

type TypesTest = UtilityFirst | UtilityLast;

const ObjJson: Exclude<TypesTest, UtilityLast> = {
    name"Front-end Gold Digger."
}
Copy the code

2. Extract

Select only UtilityLast types from the TypesTest type.

Applicable to: Union type

interface UtilityFirst {
    name: string
}

interface UtilityLast {
    age: number
}

type TypesTest = UtilityFirst | UtilityLast;

const ObjJson: Extract<TypesTest, UtilityLast> = {
    age1
}
Copy the code

3. Readonly

Convert all property values of an array or object to read-only. I’m just going to do the same thing for object chestnuts and arrays.

Applies to: objects, arrays

interface UtilityFirst {
    name: string
}

const ObjJson: Readonly<UtilityFirst> = {
    name"Front-end Gold Digger."
}
ObjJson.name = "Frogman" // A read-only error is reported
Copy the code

4. Partial

Sets all properties of the object to selected. We know that interface is not set, right? Modifier, then the object is mandatory. This utility class can convert all properties to optional.

Applies to: objects

interface UtilityFirst {
    name: string
}

const ObjJson: Partial<UtilityFirst> = {
    
}
Copy the code

5. Pick

Pick Selects some key values of the object type and extracts them. The first parameter is the target value, and the second parameter combines the key

Applies to: objects

interface UtilityFirst { name: string, age: number, hobby: [] } const ObjJson: Pick < UtilityFirst, "name" | "age" > = {name: "man ahead the nuggets," age: 18}Copy the code

6. Omit

Omit partial key values in object types and filter them out. The first parameter is the target value, and the second parameter combines the key

Applies to: objects

interface UtilityFirst { name: string, age: number, hobby: string[] } const ObjJson: Pick < UtilityFirst, "name" | "age" > = {hobby: (" code ", "badminton")}Copy the code

7. Required

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

Applies to: objects

interface UtilityFirst { name? : string, age? : number, hobby? : string[]} Const ObjJson: Required<UtilityFirst> = {name: "UtilityFirst ", age: 18, Hobby: ["code"]}Copy the code

8. Record

Create an object result set with the first argument being the key value and the second argument being the value. Specifies that we can only create field values in these fields.

Applies to: objects

Type IndexList = 0 | 1 | 2 const ObjJson: Record < IndexList, "front-end nuggets have" > = {0: "man ahead the nuggets," 1: "man ahead the nuggets," 2: "the front nuggets have"}Copy the code