Haha, actually just learning 📒

You can improve the reliability of your code

The type system

Strong and weak typing (type safety)

Strong types have stronger type constraints, while weak types have few. Strong types do not allow any implicit casting of data, while weak types allow any implicit casting of data. Language level limitations javascript is a weakly/dynamically typed language

Weak type problems

The exception is found at run time, implicit type conversions can cause a number of problems, and the strongly typed syntax phase can’t pass

The advantage of strong typing

Errors are exposed earlier — at the coding stage, the language is able to show that the code is smarter, the code is more accurate and the refactoring is more robust to reduce unnecessary type judgments

Static versus dynamic typing (type checking)

Whether the type of a variable can be changed at any time

Flow

Javascript type checker

Quick learning

NPM init -y install flow-bin in NPM init -y install flow-bin in NPM init -y

Note: To use Flow, if you are using VS Code, you need to search JavaScript Validate in setting=> to disable the automatic detection tool and install the Flow Language Support plugin

npm

Package. The json

Function sum(a: number, b: String){Copy the code

Compile removes type annotations

Flow-remove-types or @bable/core @bable/cli @bable/ PRESET -flow are two tools for removing annotations

Take NPM/Bable as an example:

NPM install --save-dev @babel/core @babel/cli @babel/preset-flow Then create a new. Babelrc file and configure presets {"presets": ["@babel/preset-flow"]} If you have all your source files in the SRC directory, compile the output directory as dist, /node_modules/. Bin/Babel SRC / -d dist/ or you can configure script {"name": "my-project", "main" in package.json: "lib/index.js", "scripts": { "build": "babel src/ -d dist/", } }Copy the code

Flow development tool plug-in

Flow Language Support

The various types of Flow

Flow primitive type

Number String Boolean Undefined NULL Symbol bigInt

Flow array type
const arr1: Array<number> = [1, 2, 3]; const arr2: number[] = [1, 23, 4]; // tuple const foo: [string, number] = ['foo', 100];Copy the code
Flow object type
const obj1: { foo: string, bar: number } = { foo: "string", bar: 100 }; const obj2: { foo? : string, bar: number } = { bar: 100 }; / / statement, can be null objects, but the definition of the data type or to obey the const obj3: {[string] : string | number} = {}; obj3.key1 = "value1"; obj3.key2 = 100;Copy the code
Flow function type

For parameter types, type annotations are added after arguments, and for function return value types, type annotations are added after function parentheses

CallBack ('100',200)} function foo(callBack (string,number)=>void){callBack('100',200)}Copy the code
Flow special type
// 字面量类型
const a: "foo" = "foo";
const type: "success" | "warning" | "danger" = "success"; 

// 或类型、联合类型
type StringORNumber = string | number; 
// 使用type关键字,type相当于给类型做一个别名 ,单独声明一个类型

const b: StringORNumber = 100;
const b1: StringORNumber = "100";

// MayBe 类型
const gender: ?number = undefined;
const gender1: ?number = null;
const gender2: ?number = 1000;
Copy the code
Flow Mixed with any)

Mixed is strongly typed. When a parameter is defined as a mixed type that is not explicitly defined as one type, it cannot be used as that type

For example: function passMixed(value: mixed){ if(typeof value === 'string'){ value.substr(1) } if(typeof value === 'number'){ value * value } }Copy the code

Any is weakly typed

Summary of Flow types

Understand the common, specific can go to query

Runtime environment API

const element: ? HTMLElement = document.getElementById(“app”); Flow can be found in the official library

TypeScript

It is progressive, and any KIND of JS operating environment supports it. Compared with Flow, it has more powerful functions and more sound ecology. Disadvantages:

  1. The language itself adds a lot of concepts (interfaces, generics, enumerations, etc.) that increase the cost of learning
  2. At the beginning of the project, TS will add some cost
Quick learning

1. After the TS module is installed, the TSC command is provided

npm init -y
npm i TypeScript --save-dev  
Copy the code

2. Package. In json

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "tsc": "tsc"
  },
Copy the code

3. Create a ts file at the end of the ts file, and you can enjoy the development. 4

The configuration file

Typescriptnpm I typescript-g is installed globally, and TSC –init initializes the tsconfig.json file to generate a basic TS configuration file

TS data type

Primitive data type
const  a:string ="foobar"
const b: number = 100   // NAN Infinity
const c: boolean = true

const d:void = undefined  //null 
const e:null = null
const f:undefined =undefined
const g :symbol = Symbol()  
Copy the code

Only “target”: “ES2015” in the tsconfig file can be used. “Target “:” ES5 “, use symbol also error, all ES6 syntax error, because this setting makes ts use the es5 standard library by default; If we must use “target”: “ES5” while also being compatible with ES6, we will need to use another lib property in the tsconfig file, and we will get to know the concept of the standard library

The standard library

“Lib “: [“ES2015”] overwrites all other default libraries, so add “lib”: [“ES2015″,”DOM”]

The standard library is the declaration file for built-in objects. When we use built-in objects in our code, we must reference the corresponding standard library, otherwise TS will not find the corresponding type

TypeScript Chinese error messages

The TSC –locale zh-cn command will change the error message to Chinese if you are using the English version

TypeScript scope issues

ES Modules, self-executing functions, and so on can handle scoping problems that can occur when variables with the same name are declared in different files

The TypeScript Object type

20 is not a generic object type. It refers to all non-primitive types, including objects, arrays, and functions

Const foo: object = function () {} // [] //{} // const obj: {foo: number, bar: string } = { foo: 123, bar: 'string' }Copy the code
TypeScript array type type
Const arr1: Array<number> = [1, 2, 3] // Array generic const arr2: number[] = [1, 2, 3]Copy the code
TypeScript tuple type

Const tuple :[number,string] =[100,’ STR ‘]

TypeScript enumeration types
Enum PostStatus {Draft = 0, Unpublished = 1, Published = 2} enum PostStatus1 {// Not specified, Draft, Unpublished, Published} enum PostStatus2 {// Specify the first, Draft = 6, Unpublished, Published} enum PostStatus3 {// String enumeration cannot be added, Draft = 'QQQQ ', Unpublished = "WWWW ", Published =" EEEE "}Copy the code

Constant enumeration

Const Draft = 0, Unpublished = 1, Published = 2}Copy the code
TypeScript function types

It’s a declaration of a function that limits its input and output by type

Function func1(a: number, b? : number, ... rest: number[]): string { // ? Optional arguments and default arguments should be placed at the end of the argument... Rest accepts any number of arguments return 'func1'} func1(100, 200, 300)Copy the code

Functional expression

// const func2: (a: number, b: number) => string = function (a: number, b: number): string {return 'func2'}Copy the code
Any TypeScript type

Any, a dynamic type, has type-safety issues, and can store other values during runtime. This means that the declared assignment is of type number, and assigning a string value is not an error because TypeScript does not type check any values

TypeScript’s implicit type inference
Let age = 18 // infer that age is of type number. Let age // infer that age is of type anyCopy the code
TypeScript type assertions

As the statement

// Assuming that this nums comes from an explicit interface const nums = [100, 120, 130, 140] const res = nums.find(I => I > 0) Number | undefined / / in the back of the operation Can use the as to assert that res must be a number won't be undefined const num1 = res as number / / or const num2 = <number>res // in JSX, <number> conflicts with HTML tags and cannot be usedCopy the code
TypeScript interface

Interface is used to constrain the structure of the object, an object to achieve an interface, it must have the interface defined in all the members of the file after the completion of compilation, no interface related code ts interface is for our structured data to do type constraints, in the actual running stage is meaningless

interface Post {
    title: string
    content: string
}

function printPost(post: Post) {
    console.log(post.title);
    console.log(post.content);
}
Copy the code

Interface member Optional, read-only, and dynamic member

interface Post { title: string content: string subtitle? :string // Optional member readOnly Summary :string // Read-only member, cannot be modified} interface Cache {// Dynamic member definition [key :string]: // Const cache: cache = {} cache.foo = 'value1'Copy the code
Use of TypeScript classes

The abstract members of a class used to describe a class of concrete objects, TS, enhance the class syntax

Class Person {name: string age: Constructor (name: string, age: const const (); // Const const (); // Const const (); // Const (); SayHi (MSG: string): void {console.log(' I am ${this.name},${MSG} '); sayHi(' I am ${this.name},${MSG} '); }}Copy the code
Class access modifier
class Person { name: string pri age: Constructor (name: string, age: const const (); // Const const (); // Const const (); // Const (); SayHi (MSG: string): void {console.log(' I am ${this.name},${MSG} '); sayHi(' I am ${this.name},${MSG} '); }}Copy the code

Access modifiers control the accessibility level of members of a class

class Student extends Person { private constructor(name: string, age: number) { super(name, age) console.log(this.gender); } static create(name: string, age: Number){return new Student(name, age)}} this constructor is private. The constructor modifier // protected that can only be created by creating a static method inside a class and then creating an object via Student.create(" Jack ",18) also cannot be instantiated compared to private Protected attributes are allowed to be inheritedCopy the code

Read-only property readonly

Class Person {public name: string // ts default is public private age: Number = 18 //private protected readonly gender: Boolean // Access qualified members only in subclasses read-only constructor(name: String, age: number) {this.name = name this.gender = true} sayHi(MSG: string): {this.name = name this.gender = true} sayHi(MSG: string): void { console.log(`I am ${this.name},${msg}`); }}Copy the code
TypeScript classes and interfaces

The interface defines methods, only for the method constraints, not the implementation

interface Eat {
    eat(food: string): void
}
interface Run {
    run(distance: number): void
}

class Person  implements Eat,Run{
    eat(food: string) {
    }
    run(distance: number) {
    }
}
class Animal  implements Eat,Run{
    eat(food: string) {
    }
    run(distance: number) {
    }
}
Copy the code
TypeScript’s abstract classes contain concrete implementations
Abstract class {eat(food: string): eat(food: string): eat(food: string): eat(food: string): Void {console.log(' purr purr eat: ${food} '); } class Dog extends Animal {run(distance: number): extends Animal {run(distance: number): extends Animal {run(distance: number): void { console.log('runrunrunrun'); }}Copy the code
Generic TypeScript

Functions are declared without specifying a type, and are called with a type that is passed to maximize code reuse

Function createNumberArray(length: number, value: number): number[] { const arr = Array<number>(length).fill(value) return arr } const res = createNumberArray(3, Function createArray<T>(length: number, value: T): T[] {const arr = Array<T>(length).fill(value) return arr} const res1 = createArray<string>(3,'foo'Copy the code
TypeScript type declarations

When a third party NPM module is not necessarily written in TS and therefore does not necessarily have a strongly typed experience, such as installing Lodash, we need to install NPM i@types /lodash –dev

import { camelCase } from 'lodash'
declare function camelCase(input: string): string 
const res  = camelCase("hello world")
Copy the code

Conclusion: in the ts, we need to introduce third-party modules, if the module does not include the corresponding type declaration documents, we will try to install the corresponding type declaration module, generally is @ types/module, if there is no corresponding module, the use of this time is our manual declare statement to declare the corresponding module type