preface

Supersets: There is no problem writing JS in TS. Features:

  1. Type annotation and compile-time type detection
  2. Class-based object-oriented programming
  3. The generic
  4. interface
  5. Declaration file

The environment

The installation

npm i -y

npm i -g typescript

Ts compiler command tsc-h

Check: TSC-V

Ts init folder TSC –init

Build tool configuration NPM I webpack webpack-cli webpack-dev-server -d

Install NPM I ts-loader typescript -d

Install NPM I html-webpack-plugin -d on the first page of the template

The command

–outdIR Specifies the output directory

–target ES6 specifies the code version target to compile

— Watch runs in listening mode and automatically compiles files when they change

-p Specifies a configuration file

/ / json configuration
{
  "compilerOptions": {
     "target": "es5"."watch": true."outDir": "./dist"
  }
  "include": ["./src/**/* "]}Copy the code

Strong and weak language

define

Statically typed language: The types of all variables are determined at compile time

Dynamically typed language: The types of all variables are determined at execution time

Comparison of data types

Type annotations

Function: Equivalent to type declarations in strongly typed languages

Syntax: (variable/function) : type

Enumeration enum

Application: in the program is not easy to remember the hard code, easy to change constants extracted from the specified enumeration type enumeration member name into value, reverse mapping principle

Digital enumeration

enum Role { 
    Reporter = 1,
    Developer,
    Maintainer,
}
/ / the compiled
"use strict";
var Role;
(function (Role) {
    Role[Role["Reporter"] = 1] = "Reporter";
    Role[Role["Developer"] = 2] = "Developer";
    Role[Role["Maintainer"] = 3] = "Maintainer";
})(Role || (Role = {}));

Copy the code

String enumeration

Enumerations of strings cannot be backed off

enum Message { 
    Success = 'Congratulations on your success.',
    Fail = 'Sorry, failed.'
}
/ / the compiled
"use strict";
var Message;
(function (Message) {
    Message["Success"] = "\u606D\u559C\u4F60\u6210\u529F\u4E86";
    Message["Fail"] = "\u62B1\u6B49\uFF0C\u5931\u8D25\u4E86";
})(Message || (Message = {}));
Copy the code
readonly id: number
Copy the code

interface

interface List {
    id: number,
    name: string
}

       
       
      
render(<Result>{
    data: {}})// The index to enter
// The return value of the numeric index must be a subtype of the return value of string traction, because type conversions are found
[x:number]:string
Copy the code
function add6(x:number,y=0; z:number,q=1) {
    return x+z+y=q
}
console.log(add6(1.undefined.3)) / / 5

function add7(x:number,... rest:number[]){
    return x+rest.reduce((pre,cur) = > pre+cur)
}
console.log(add7(1.2.3.4.5)) / / 15
Copy the code

Data type reorganization (function overloading)

function add8(. rest:number[]) :number;
function add8(. rest:string[]) :string;
function add8(. rest:any[]) :any {
    let first = rest[0];
    if(typeof first == 'string') {
        return rest.join(' ')}if(typeof first == 'number') {
        return rest.reduce((pre,cur) = > pre+cur)
    }
}
console.log(add8(1.2.3)) / / 6
console.log(add8('a'.'b'.'c')) //abc
Copy the code

class

The properties of class members are instance properties rather than stereotype properties, and the methods of class members are instance methods

  1. Super () — instance of the parent class (derived class constructor must contain a call to super)
  2. Private – This class cannot be instantiated or inherited. Private members can only be called within the class itself, not by instances or subclasses of the class
  3. Protected — This class cannot be instantiated but can only be inherited. Protected members can only be used in classes and subclasses
  4. Readonly – Read-only property (not allowed to be modified), must be declared in advance
  5. Public — instantiate attributes
class Dog {
    constructor(name:string) {
        //protected constructor(name:string) the constructor can also be protected, indicating that it cannot be instantiated, only inherited
        this.name = name
    }
    public name:string = 'dog'
    run() {}
    private pri() {} // Set the private member
    protected pro(){} // Protected member
    readonly legs:number = 4; // Read-only properties cannot be changed and need to be initialized, just like instance properties
    static food:string = 'bones'// A static member of a class that can only be called by the class name, not by subclasses
}
let dog = new Dog('wang') / / instantiate
console.log(Dog.food) // Static class name called successfully
// console.log(dog.food) // Static subclass call failed
//dog.pri() // cannot be called in an instance of the class
class Husky extends Dog {/ / inheritance
    constructor (name:string,color: string) {// init in the constructor
        super(name) // The derived class constructor must contain a call to super
        this.color = color; // This can only be used after super
        //this.pri() // The subclass call failed
    }
    color: string // Declare color after constructor instantiation and call this,
    // constructor (name:string,public color: string) constructor (name:string,public color: string
}

Public Public members (default, all visible) private private members () protected members (only accessible in classes and subclasses, Applications cannot be instantiated in constructors only inherit) ReadOnly Read-only properties (need to be initialized) static Static members (can only be called by class name) */

Copy the code

An abstract class

It can only be inherited, but not instantiated. Abstract abstracts the commonality of code, facilitates the reuse and expansion of code, and can also realize polymorphism

// The obvious symbol of an abstract class, abstract
abstract class Animal {
    // Define a method in the abstraction to implement method reuse
    eat () {
        console.log('eat')}// Do not specify concrete method implementation, abstract method, explicitly subclass has other implementation
    abstract sleep():void
}
class DD extends Animal {
    constructor(name:string) {
        super(a)this.name = name
    }
    name: string
    run() {}
    sleep() {
        console.log('dog')}}let dd = new DD('wang');
dd.eat();

// Implement polymorphism
class Cat extends Animal {
    sleep() {
        console.log('Cat')}}let cat = new Cat();
let animal:Animal[] = [dd,cat]
animal.forEach(i= > {
    i.sleep(); // Execute different method contents through a loop
})

/ / column type
class WorkFlow {
    step1() {
        return this;
    }
    step2() {
        return this; }}new WorkFlow().step1().step2(); // Implement a column call to the method, where polymorphic this is the parent or child type

class Myflow extends WorkFlow {
    next() {
        return this; }}new Myflow().next().step1().next().step2()// Ensures consistency between subclass and superclass interface calls

Copy the code

Relationships between classes and interfaces

An interface

  1. You can constrain the number of attributes and types of class members
  2. Only public members can be bound. If private, an error is reported
  3. Constructors cannot be constrained, only public members of a class
  4. Multiple interfaces can be inherited
/ / interface
interface Human {
    //new (name:string):void; // New (name:string):void
    name: string;
    eat(): void
}
/ / class
class Asian implements Human {
    constructor(name:string) {
        this.name= name
    }
    name: string;
    eat() {} // A class that implements an interface needs to implement all properties declared in the interface
    slepp(){} // You can declare one yourself
}
interface Man extends Human {
    run():void
}
interface Child {
    cry():void
}
// Interface inheritance can merge multiple interfaces into one
interface Boy extends Man,Child {

}
let boy:Boy = {
    name: ' '.run() {},
    eat() {},
    cry(){}}// An interface abstracts the members of a class
class Auto  {
    static = 1
    private static2 = 0 // C is not a subclass of C, so it cannot inherit its private member
 
}
interface AutoInterface extends Auto {

}
class C implements AutoInterface {
    static = 1
}
class Bus extends Auto implements AutoInterface {}Copy the code

Generic functions and generic interfaces

Definition: Data types that are not defined in advance. The specific type is determined at the time of use.

  1. Original [functions and classes need to support multi-attribute types with high flexibility]

2. Progressively change to an array that accepts strings

or

3. Change to accept any type of data

An implementation of the any type loses some information about the type’s direct constraints. 4

Generic implementation cases

class Log<T> {
    run(value:T) {
        console.log(value)
        return value
    }
}
let log1 = new Log<number> ()
log1.run(7)
let log2 = new Log()
log2.run('1')

interface Length {
    length:number
}
function log<T extends Length> (value:T) :T {
    console.log(value,value.length)
    return value
}
log([1])
log('123')
log({length:1})
Copy the code

Generic benefits

  1. Functions and classes can easily support multiple types, increasing the extensibility of programs
  2. There is no need to write multiple function overloads to enhance readability
  3. Flexible control of constraints between types

Type protection mechanism

Type inference

Definition: enter var I = 6 where it can be inferred that the attribute type of I is number

Type compatibility

X compatibility Y: x (target type) = Y (source type) Compatibility between structures: compatibility with fewer members Compatibility with functions with more members: compatibility with more parameters compatibility with fewer parameters

interface Point3 {
    x:number;
    y:number;
    z:number
}
interface Point2 {
    x: number;
    y:number;
}
let p3d = (point:Point3) = > {};
let p2d = (point:Point2) = > {};
p3d = p2d // More parameters are compatible with less parameters
p2d = p3d // is not compatible

// Return value type
let f =() = > ({name:'A'})
let g =() = > ({name:'A'.location: 'B'})
f=g // More compatible members with fewer members
Copy the code

Type of protection

Definition: TS can guarantee that a variable is of a certain type in a specific area, and can safely refer to properties of that type or call methods of that type in this area.

enum Type{Strong,Week}
class Java {
    hellowJava() {
        console.log('Hellow Java')}}class JavaScript {
    hellowJavaScript() {
        console.log('Hellow JavaScript')}}function getLanguage(type:Type) {
    let lang = type === Type.Strong?new Java():new JavaScript();

    // instanceof determines whether an instance belongs to a class
    if( lang instanceof Java) {
        lang.hellowJava()
    } else {
        lang.hellowJavaScript()
    }
    
    return lang;
}
getLanguage(Type.Strong);
Copy the code

Advanced types – cross types and union types

Cross type: Merge multiple types into a single type. The new type will have all the type characteristics and is suitable for mixing scenarios. This is the union of all types.

interface D {
    run():void
}
interface B {
    jump():void
}
let pet:D&B = {
    run() {},
    jump(){}}Copy the code

Union type: The declared type is not determined to be one of multiple types.

let a:number | string = 'a' // Can also be 1
Copy the code

Advanced type – Index type

Query and access to object properties in conjunction with generic constraints to create object properties.

let obj = {
    a: 1.b: 2.c: 3
}
function getValues<T.K extends keyof T> (obj: T,keyS:K[]) :T[K] []{
    return keyS.map(key= > obj[key])
}
console.log(getValues(obj,['a'.'b']))
//console.log(getValues(obj,['ew','w']))
Copy the code

Advanced types – Map types

The old type generates a new type. (the default)

Advanced types — Conditional types

Make the content of the result not unique, increase the flexibility of the language.

// Distributed condition type
// (A|B) extends U? X:Y
// A extends U? X:Y) | (B extends U? X:Y)

type Diff<T,U> = T extends U ? never : T
type T4 = Diff<"a" | "b" | "c" ,"a" | "e" > //type T4 = "b" | "c"
/ / deconstructed the Diff (" a ", "a" | "e" > | Diff < "b", "a" | "e" > | Diff < "c", "a" | "e" >
// never | "b" | "c" 
// "b" | "c"


// Filter undefined and null
type NotNull<T> = Diff<T,undefined | null >
type T5 = NotNull<string | number | undefined |null>
//Extract
type T6 = Extract<"a" | "b" | "c" ,"a" | "e" > //a

// ReturnType Return value type
type T7 = ReturnType<() = > string > //string
 Infer means to infer or infer
Copy the code

Es6 and CommonJS

// Export separately
export let a = 1
// Batch export
let b = 2
let c = 3
export {b,c}
// Export interface
export interface P {
    x:number;
    y:number;
}
// Export the function
export function f() {}
// Alias the export
function g() {}
export {g as G}
// Export by default, no function name required
export default function () {
    console.log("I'm default")}// Import the external module and export again
export {str as hello} from './b'
/ / import
let c1 = require('./a.node')
Copy the code

The namespace

A namespace must come after a function or class definition when it is merged with a function declaration or a class declaration

namespace Shape {
   export function square(x:number) {
       returnx * x ; }}console.log(Shape.square(1));
Copy the code

A statement to merge

The order in which the function is declared is an independent variable. The parameters of the function are determined sequentially within the interface

interface A {
    x : number // Non-functional state
    foo (bar:number) : number; // Function state overload 5
    foo(bar:'a'):number; / / 2
}
interface B {
    y: number;
    foo (bar:string):string; / / 3
    foo(bar:number[]):number[];  / / 4
    foo(bar:'b'):number; / / 1
}
let a:A = {
    x:1.y:1
    foo(bar:any) { // Function overload implementation
        return bar
    }
}
Copy the code

Declaration file

When using a non-TS class library, you must declare a file for the class library that exposes the API. You can use TypeSearch to check if there are related library files

Configuration tsconfig

{" files ":"src/a.ts"]."include" : [
        "src"]."exclude" : [
        "src/lib"]}Copy the code

Compilation tools – from TS-Loader to Bable

The TypeScript and ESLint

Both successively convert to AST syntax trees when converting, resulting in recognition conflicts that push typescript-ESLint from the original lineage

Tool system

Pay attention to

  1. Private private: When a member is marked private, it can no longer declare external access to its class
  2. Protected Protecte: protected members are still accessible in derived classes
  3. Read-only Readonly: The read-only property must be initialized at declaration time or in a constructor
  4. Parameter properties: Adding modifiers to constructor parameters defines and initializes a member property
class features {
    // Here we need to initialize, one by one, so use the constructor
    constructor(public id: number,public name: string){}}Copy the code
  1. Accessors: Accessors (also called getters, setters) can be used when there is extra logic to get and set properties
class Employee {
    private firstName: String = 'Mike' ;
    private lastName: String = 'James';

    get fullName() :string {
        return this.firstName + ' ' + this.lastName
    }

    set fullName(newName: string) {
        console.log('You changed the username');this.firstName = newName.split(' ') [0];
        this.lastName = newName.split(' ') [1]; }}const employee = new Employee();
employee.fullName = 'Bon smit'
Copy the code

In actual combat

Create a project

Install command NPX create-react-app project name –typescript

Load file configuration on demand

Antd config-overrides. Js file

Type constrained React component development

React class components inherit from Component components

Higher-order components with Hooks

Problem: The default properties of the encapsulated HelloClass component cannot be passed to higher-order components, only the interface properties defined can be set to optional. Note: 1. Type issues (React is not yet well compatible with higher-order component detection)