[Typescript] theory + practice code record

Posted by Megahertza on Mon, 03 Jan 2022 05:47:09 +0100

typescript

Dynamically typed languages: errors are known only when running

Statically typed languages: compilation phase

1. Advantages

  1. Provides a static type style type system
  2. We used babel to compile the syntax support from es6 to es10
  3. Compatible with various browsers, systems and servers

2. Why use ts?

  1. The program is easier to understand

Previous questions: input and output parameter types of functions or methods, external conditions

Constraints of dynamic language: manual debugging and other processes are required

The code itself can answer the appeal question

  1. More efficient
    Jump in different code blocks and definitions

Automatic code completion

Rich interface tips

  1. Fewer errors
    Most errors can be found during compilation

Eliminate some common mistakes
4. Very good compatibility

Fully compatible with js

Third party libraries can write type files separately

All popular projects support ts – react vue ant design

3. Deficiencies:

  • Increase learning cost interface
  • Increased development costs

4. js type

javascript basic types
7 original types
Boolean
Null
Undefined
Number
Bigint
String
Symbol

Object

The string operation in javascript must return a new string, and the original string has not changed

5. Define these primitive types in ts:

let isDone: boolean = false

let age: number = 3

let binaryNumber: number = 0b111

let first: string = 'vin'

let message: string = `h${first}`

let u: undefined = undefined

let n: null = null

let num: number = undefined

6. Any type: pass There is no automatic prompt method

let notSure: any = 4
notSure = 'jing'
notSure = false
notSure = 6
notSure.myname
notSure.myFn()
// notSure.  No hint

7. Joint type

let numberOrString: number | string
numberOrString = 'aaa'
numberOrString = 3
// numberOrString = false error

8. Array:

let arrOgNumber: number[] = [1, 2, 3]
// arrOgNumber.push('5 ') error
arrOgNumber.push(5)

9. Tuple

let user: [string, number] = ['jing', 30]
user = ['jing'] // report errors
user = ['jing', 2, 3] // report errors
// More and less will report an error

10. interface:

  1. Describe the shape of the object
  2. Abstract classes
  3. Duck type
interface Person {
    name: string;
    age: number;
}
let jing: Person = {
    // Not without many attributes
    name: 'jing',
    age: 22
}

11. Optional attribute:?

interface Person {
    name: string;
    age?: number;
}
let jing: Person = {
    name: 'jing',
    // age: 22 no error
}

12. Read only attribute readonly

interface Person {
    readonly id: number
    name: string;
    age?: number;
}
let jing: Person = {
    // Not without many attributes
    id: 1,
    name: 'jing',
    // age: 22
}

jing.id = '111' // Error readonly 

readonly is used on properties
const is used on variables

Function type:

// function add(x: number, y: number,z?: number): number {
//     return x + y
// }
// add(1, 2, 3)

const add = function(x: number, y: number,z?: number): number {
    return x + y
}
add(1, 2, 3)

// Declared function return value = >
const add2: (x: number, y: number, z?: number) => number = add

13. Type inference:

let str = 'str'
str = 123 // Error ts compilation inference str is a string type

14. class

Class: an abstract concept that defines everything
Objects: instances of classes
Object oriented: encapsulating inheritance polymorphism

class Animal {
    name: string;
    constructor(name: string) {
        this.name = name
    }
    run() {
        return `${this.name} is running`
    }
}

const dog = new Animal('jing')
console.log(dog.name)

class Dog extends Animal {
    bark() {
        return `${this.name} is barking`
    }
}

const wang = new Dog('zhihao');
console.log(wang.name, wang.bark) 
// jing
// zhihao [Function: bark]

class Cat extends Animal {
    // super is used when a subclass calls a parent class
    constructor(name: string) {
        super(name)
        console.log(name) // jj
    }
    // The subclass overrides the run method of the parent class
    run() {
        return 'ming' + super.run()
    }
}

const zhi = new Cat('jj')
console.log(zhi.run())
//mingjj is running

public can be used
private can only be used inside class
Protected (only subclasses can be used, but the instances from new cannot be used)
readonly can only be read and cannot be modified
static

class Animal {
    name: string;
    static zhihao: string[] =
        ['am', 'hi']
    static isAnimal(a: any) {
        return a instanceof Animal
    }
    constructor(name: string) {
        this.name = name
    }
    public run() {
        return `${this.name} is running`
    }
}

const dog = new Animal('jing')
console.log(Animal.zhihao) // [ 'am', 'hi' ]
console.log(Animal.isAnimal(dog)) // true

15. interface implements to verify the properties and methods of the class

interface Radio {
    switchRadio(): void;
}
interface Battery {
    checkBatteryStatus(): void;
}

// Merge the above two interfaces:
interface RadioWithBattery extends Radio {
    checkBatteryStatus()
}
class Car implements Radio{
    switchRadio() {

    }
}

// class Phone implements Radio is used after merging
class Phone implements Radio, Battery{
    switchRadio() {
        
    }
    checkBatteryStatus() {

    }
}

16. enums

Using const constant enumeration can improve performance

const enum Direction {
    up = 'up',
    down = 'down',
    left = 'left',
    right = 'right',
}

const value = 'up'
if (value === Direction.up) {
    console.log('go up')
}

Compiled code

No const

var Direction;
(function (Direction) {
    Direction["up"] = "up";
    Direction["down"] = "down";
    Direction["left"] = "left";
    Direction["right"] = "right";
})(Direction || (Direction = {}));
var value = 'up';
if (value === Direction.up) {
    console.log('go up');
}

Use const

var value = 'up';
if (value === "up" /* up */) {
    console.log('go up');
}

17. Generic constraints

function echoWithArr<T>(arg: T[]): T[] {
    console.log(arg.length)
    return arg
}

const arrs = echoWithArr([1,2,3])

As long as the length defined on the interface exists

interface IwithLength {
    length: number
}

function echoWithLength<T extends IwithLength>(arg: T): T {
    console.log(arg.length)
    return arg
}

const str = echoWithLength('str')
const obj = echoWithLength({ length: 10 })
const arr2 = echoWithLength([1, 2, 3])
const num = echoWithLength(1) // A parameter of type 'number' cannot be assigned to a parameter of type 'IwithLength'

class I + generic

class Queue<T> {
    private data = [];
    push(item: T) {
        return this.data.push(item)
    }
    pop() : T {
        return this.data.shift()
    }
}

const que = new Queue<number>()
que.push(1)
// que.push('str')
console.log(que.pop().toFixed())
console.log(que.pop().toFixed())

const que1 = new Queue<string>()
que1.push('1');
console.log(que1.pop().length)

interface KeyPair<T, U> {
    key: T
    value: U
}
let kp1: KeyPair<number, string> = { key: 1, value: "str" }
let kp2: KeyPair<string, number> = { key: 'text', value: 1 }

II array + generic

let arr: number[] = [1, 2, 4]
let arrTow: Array<number> = [1, 2, 3]

Ⅲ function + generic

interface IPlus<T> {
    (a: T,b: T) : T
}
function plus(a: number, b: number): number {
    return a + b;
}
function plus1(a: string, b: string): string {
    return a + b;
}
const a: IPlus<number> = plus
const b: IPlus<string> = plus1

18. Type alias

Alias a function

type PlusType = (x: number,y: number) => number
function sum(x: number, y: number): number {
    return x + y
}
const sum2: PlusType = sum

When using union types:

type NameResolver = () => string
type NameOrResolve = string | NameResolver
function getName(n: NameOrResolve): string {
    if (typeof n === 'string') {
        return n
    } else {
        return n()
    }
}

19. Function assertion

If the as keyword is used to fit the type, it can only set the common attributes of the two channel types. You can use the as attribute to get the values we need to use

function getLength(input: string | number): number {
    const str = input as String
    if (str.length) {
        return str.length;
    } else {
        const number = input as Number
        return number.toString().length
    }
}

Topics: Front-end TypeScript