TypeScript

In order to cooperate with Vue3, I reviewed JavaScript yesterday and then learned TypeScript today. Since asynchronous Promise was not involved, it was easy to learn.

1. Install the TS and configure the operating environment

NPM install -g typescript is used to download ts files, and TSC xxx.ts is used to compile ts files into JS files. But if I wanted to run ts files directly in WebStorm, I would have to configure them differently.

Install the environment first

npm install -D typescript
npm install -D ts-node
npm install -D @types/node
Copy the code

Configure the run Settings

Then go to the plugin and install Run Configuration for typescript

After rebooting WebStorm, you can click to run the.ts file as before

2. Some BASIC KNOWLEDGE of TS

2.1 About data types

2.1.1 Basic Types

As in most languages, TS’s base data types include booleans, values, strings, null, undefined, as well as the new type Symbol in ES6 and the new type BigInt in ES10, where Boolean is Boolean, values are number, and strings are string

In addition, if we want to restore the flexibility of JS, we can define the data type as any, that is, can be assigned to any type, TS will not be defined as string and then assigned to int error. When we define a variable without assigning it, TS will infer that the variable is of type any. This avoids type checking and allows for flexible assignment later.

If there is no initial assignment there is no type inference and any subsequent assignments will not go wrong

2.1.2 Association type

If we want a variable that can be assigned to string and number, but not to any other type, we can, and we need to use associative types

Using | will be two types of separated can allow multiple types

2.1.3 interface

Interface is used to define abstract methods in object-oriented, in TS in addition to the method of the class can be abstracted, but also on the property of the provision.

interface Man{
    name:string
    age:number
}

let a:Man={
    name:"a".age:18
}

console.log(a)
Copy the code

In this case, our assignment variable can have neither more nor fewer attributes. But everyone is different, so you need some optional attributes.

interface Man{
    name:string
    age:numberalive? :boolean
}

let a:Man={
    name:"a".age:18.alive:true,}let b:Man={
    name:"b".age:99,}console.log(a)
console.log(b)
Copy the code

In this case our alive property is optional, it may not exist, but it still cannot be added. There’s nothing you can’t do, right? We’ve seen before that any can define any type, but it can also define a type that doesn’t exist.

interface Man{
    name:string
    age:numberalive? :boolean
    [xxx:string] :any
}

let a:Man={
    name:"a".age:18.alive:true.work:"student"
}

let b:Man={
    name:"b".age:99.email:"[email protected]"
}

console.log(a)
console.log(b)
Copy the code

Of course, you can still define read-only properties, which can only be read and cannot be modified.

2.1.4 array

Let arr:number[]=[1,2,3,4]. Let arr1:Array

=[5,10,15]

let arr:number[] = [1.2.3.4]
let arr1:Array<number> = [5.10.15]
arr.push(11)
console.log(arr,arr1)
arr.pop()
console.log(arr)
Copy the code

2.1.5 function

There are three ways to define a function

  • Function declaration
  • Functional expression
  • = > function
function sum1(x:number,y:number) :number{
    return x+y
}

let sum2=function (x:number,y:number){
    return x+y
};

let sum3=(x:number,y:number) = >x+y;

let a:number=15
let b:number=16

console.log(sum1(a,b))
console.log(sum2(a,b))
console.log(sum3(a,b))
Copy the code

// Optional parameters and default values
function Print(str:string,age:number=18,str2? :string){
    if(str2){
        console.log(str+` ${age} `+str2)
    }else{
        console.log(str+` ${age} `)
    }
}

Print("aaa")
Print("bbb".1)
Print("bbb".1."ccc")
Copy the code

2.2 Common Contents

2.2.1 Creating an Alias

Type New name = original data type

2.2.2 Literal restrictions

From create an alias to restrict, when will the alias used | so you can make an alias can only choose among several limited value.

2.2.3 Ancestor & Enumeration

We use meta-elements to combine different types of elements

let person:[string.number] = ['aaa'.18]
console.log(person)
// Assign a separate value
let a=[]
a[0] =1
a[1] ='aaa'
console.log(a)
// Two values must be assigned at the same time
a=[12.'bbb']
console.log(a)
Copy the code

Enumerations, like any other language, are self-incrementing

enum Days{Mon=1,Tue,Wed,Thu,Fri,Sat,Sun}

function Print1(){
    for(let i=1; i<=7; i++){console.log(Days[i])
    }
}

let names:Array<any> = ["Mon"."Tue"."Wed"."Thu"."Fri"."Sat"."Sun"]
names.forEach((val) = >{
    console.log(Days[val])
})


Print1()
Copy the code

2.2.4 Classes and Interfaces

interface Do{
    sleep(h:number) :string
}

class Person implements Do{
    name:string
    constructor(name:string) {
        this.name=name
    }

    say(sth:string) :string{
        return `My name is The ${this.name},and ${sth}`
    }

    sleep(h:number) :string{
        return ` slept${h}Hours `}}let a:Person=new Person("aaa")
console.log(a.say("I'm Unhappy!"))
console.log(a.sleep(10))
Copy the code

2.2.5 generic

function createArray<T> (length:number,value:T[]) :Array<T>{
    let result:T[]=[]
    for(let i=0; i<length; i++){ result[i]=value[i] }return result
}

console.log(createArray<number> (5[3.4.5.7.5.1]))

function swap_diff<T.U> (tuple:[T,U]) :U.T]{
    return [tuple[1],tuple[0]]}console.log(swap_diff(['aaa'.18]))
Copy the code