typescript

Why typescript

Js is a dynamic data type, so data type verification cannot be carried out. As a result, we may not know the meaning of this line of code and what parameters need to be passed when we contact other people’s code, which leads to the difficulty of code writing and the increase of bugs.

So we have typescript, the super JavaScript, the non-dynamically typed language, the statically typed language.

To solve this situation, to achieve correctness, maintainability.

What is typescript?

As can be seen above, TS is super JS, is statically typed, is a language that can contract data types.

Its most obvious and central role is that of the convention data type.

Because it is “convention”, so, when we write data, we must put the data type to bring, and match correctly, if not correct, will report an error!

How is typescript used?

Based on using

1. Common type usage

String, number, array of the same type, array of different types

let name: string = 'name'

let age:number = 12

let happy:boolean = true



let address: string[] = ['chengdu'.'beijing']

let likes: [string.number] = ['hahaha'.12]
Copy the code

2. Use undefined and null

let student: undefined = undefined

let student: null = null

let student: string = undefined

let student: string = null
Copy the code

3. Balm type: any

let studeng: any = 'haha'
let studeng: any = 1212
let studeng: any = [1.2.3]
let studeng: any = [1.'haha'.undefined]
let studeng: any = undefined
let studeng: any = null
let studeng: any = {}
Copy the code

4. Union types

If we are not sure what the type is, but can lock on to which types, we can use the union type to indicate that it can be both type X and type Y!

let haha: string | number = 12
let haha: string | number = 'hahha' 
// Can be either number or string
Copy the code

Interface to use

Basic usage of interfaces

interface Person{
  readonly id: number;
  name: string;
  age: number; The address? :string[];
}

let rose: Person={
  id: 1.name:'rose'.age:19.address: ['chengdu'.'shanghai']}Copy the code

The interface is used as above, and also uses readonly and? :

Readonly: If we have a property that we do not wish to modify and is read-only, we can use readonly to constrain it! If we try to change this value, we get an error!

? If we have a value that can be used or not, then we can add a value to the property. .

Which common interfaces can be used?

Our arguments x,y, and z must be of type number. , so the z argument is passable or not), and the return value of this function must also be of type number.

function add(x: number, y: number, z? :number) :number{
  return x+y+z
}

const total = add(1.2.3)
const total = add(1.2)


Copy the code

Our add2 value is of type (x:number, y:number, z? :number), and the return value is number, add2 equals add.

The purpose of this notation is to check the add method. The parameter types and return values of add2 are the same as those of add.

let add2: (x:number, y:number, z? :number) = > number = add
Copy the code

Interface interface interface interface interface interface interface interface

ISum usually we put an I in front of something defined by interface to indicate that it’s defined by interface.

interface ISum {
  (x:number.y:number, z? :number) :number
}

let add2: ISum = add
Copy the code

If the arguments passed by our function are uncertain and can be either string or number, then we can use the union types we learned above!

The as keyword can force our type to be xx!

function getLength(input: string | number) :number{
  const str = input as string
}
Copy the code

Use of the Class Class

What are the use scenarios for class? What’s the use of what we learned?

The React component is written in class.

1. Use of the Class base

class Animal {
  readonly name: string;
  constructor(name){
    this.name = name
  }
  run(){
    return `The ${this.name}is running! `}}Copy the code

In React, for example, we can use readonly for state!

2. Interface inheritance in Class

Implements and extends

  1. A class can implement an interface, and if it implements an interface, it must implement the methods it implements!
  2. Our class can inherit multiple interfaces at the same time. implements
  3. Interfaces can inherit from interfaces! extends
// We wrote an interface that implements a method called switchRadio, which passes a Boolean trigger and returns no value!
interface Radio{
  switchRadio(trigger: boolean) :void;
}

interface Battery {
  checkBatteryStatus(): void;
}

interface RadioWithBattery extends Radio{
  checkBatteryStatus(): void;
}

class Car implements Radio{
  // Radio implements switchRadio, we must implement this method!
  switchRadio(trigger: boolean){}}// Can inherit multiple interfaces!
class Car implements Radio.Battery{
  // Every method implemented in the interface must be implemented!
  switchRadio(trigger: boolean){}checkBatteryStatus(){}}Copy the code

Enumeration enum

By default, our EUNM is a number, starting at zero and going from there.

However, it is not easy to use. In order to better use, we often assign a string value to the value in the enumeration, so that the meaning of the value is more suitable for our business and a better logical judgment.

enum Direction {
  Up = 'Up',
  Down = 'Down',
  Left = 'Left'
  Right = 'Right'
}

if('Up' === Direction.Up){
   
}
Copy the code

Paradigm Generics

Like a placeholder, the type is dynamically filled in at the time of use!

function echo<T> (echo: T) :T{
  return echo
}

function swap<T.U> (tuple:[T,U]) :U.T]{
  return [tuple[1], tuple[0]]}Copy the code
function echoWithArr<T> (arg: T[]) :T[]{
  console.log(arg.length) // Array has length property, is correct ha!
  return arg
}

//---------
function echoWithArr<T> (arg: T) :T{
  console.log(arg.length) // An error will be reported!
  return arg
}
echoWithArr('hahhahahah')// An error will be reported! But our string does have a length attribute. What to do?
//------------

interface IWithLength {
  length: number;
}
function echoWithLength<T extends IWithLength> (arg:T) :T{
   console.log(arg.length)
  return arg
}
echoWithArr('hahhahahah') // This is not an error.
Copy the code

Use of stereotypes in classes and interfaces

We’ve agreed that the T in Queue is number

class Queue<T> {
  private data=[];
  push(item: T){
    return this.data.push(item)
  }
  pop():T{
    return this.data.shift()
  }
}
const queue = new Queue<number> ()Copy the code

Type Type alias

Type is interface’s buddy! They share similar usage scenarios, but have some different characteristics.

The use of the type

  1. If we need to specify defaults
  2. If our value can only be one of these defaults
  3. Consolidation types
const str: 'name' = 'name'
const num: 1 = 1

// If our value can only be one of these default values
type Directions = 'Up' | 'Down' | 'Left' | 'Right'
let own: Direction = 'Left'


// Cross types
interface IName{
  name: string
}
type IPerson = IName & {age: number}
const person:IPerson = {
 	name:'rose'.age:18
}
Copy the code

How to select Type and interface

  1. If you want to use extends and implements, you choose Interface
  2. If you want to implement the default type, cross type, you can select Type

What’s good/bad about typescript?

Benefits: The convention type, solve the type is not clear when the unmaintainability, improve code maintainability, readability.

Cons: Cost of learning!