Overview of TypeScript

TypeScript is a programming language based on JavaScript. It addresses the problem of JavaScript’s own type system. Using TypeScript’s language makes your code much more reliable;

Type system

Before we tackle the JavaScript type system, let’s explain two sets of nouns that distinguish different programming languages:

  • Strong and weak typing, which distinguishes different programming languages from each other in terms of type safety
  • Static and dynamic typing, which type checking uniquely distinguishes between programming languages
1. Type safety

From the perspective of type safety, programming languages are divided into strongly typed and weakly typed.

  • Definition of strong typingFrom:Language levellimitfunctionArgument typeMust be connected toParameter type Exactly the same

  • Definition of weak typesFrom:Language level There is no restriction on the type of argument

  • Because of this type of strong and weak pointsThe fundamentalIt’s not just a definition of authority; There are better ways to identify:
    • Strong types have stronger type constraints, while weak types have few constraints;
    • In other words: strongly typed languages do not allow arbitrary implicit type conversions; Weakly typed languages allow any implicit data conversion
  • Variable types are allowed to change at any time, not strong and weak type differences;
1. Type check

From the perspective of type checking, it can be divided into: statically typed language and dynamically typed language

  • Characteristics of statically typed languagesWhen a variable is declared, its type isclear; Once declared, its type cannot be changed;
  • Characteristics of dynamically typed languagesIn:Operation phaseIn order toclearThe type of a variable, if it changes it can change at any time; You can also say: dynamically typed languagesThe variable has no typeIs stored in a variableValues are typed
3. Classification of desired languages in the type system

3. Features of JavaScript type system

Because JavaScript is a weakly typed and dynamically typed language; The language’s own type system is so weak that JavaScript doesn’t have a type system at all; The language is characterized by a popular word: humanity; Because it has almost no type of restrictions, all JavaScript languages are extremely flexible; However, the reliability of type system is missing behind the appearance of flexibility and variability.

  • Why isn’t JavaScript strongly typed/statically typed?
    • The early days of JavaScript were simple to use, the early days of JavaScript were very simple and small in scale
    • JavaScript is a doorScripting language.You don't need to compile, run directly in the operating environment; JavaScript doesn’t compile, and it doesn’t make sense to be statically typed; Because statically typed languages need to be inCompilation phaseType check;
    • On a large scale, this [advantage] becomes a weakness

Fourth, weak type problems

  • In the weakly typed language of Javascript,You have to wait until the run phaseAnd instead of executing the foo method right away, execute it at a specific time. For example, if we put it in a setTimeout, it won’t execute until the setTimeout executes. A strongly typed language calls a member of an object that doesn’t exist here, and it’s syntactically wrong;
Const obj ={} obj.foo() const obj ={} obj.foo() const obj ={} obj.foo() const obj ={} obj.foo();Copy the code
  • Type is uncertain, resulting in function function changes;
Function sum(a, b) {return a +b} console.log(100, 100) // ok console.log(100, '100'); // Sum is the sum of the two numbers. If we are playing with two numbers, the result will be normal, but if we are passing in a string, then our function will completely change, and it will return the result of concatenating the two strings. // Some people say that we can avoid this problem through our own conventions. Indeed, we can avoid this problem through conventions. // However, you should know that conventions are not guaranteed at all, especially in the case of open groups of people. There is no way to guarantee that everyone will follow all causes, and in strongly typed languages, this situation is completely avoided, because in strongly typed languages, if you pass in numbers, then you pass in other types of values, which is not syntactically possible.Copy the code
  • An incorrect use of an object indexer
Const obj ={} obj[true] = 100 console.log(obj['true']) // Create an object and add attributes to the object using the indexer syntax. So we can use any type of value as an attribute in the index, and its contents will be automatically converted to a string; For example, if obj adds true as its property, then the final object's actual property is the string's trueCopy the code

Conclusion: The disadvantages of weakly typed language are obvious, but in the case of small amount of code, these problems can be avoided by convention, and for some large-scale projects with a particularly long development cycle. Gentleman’s agreement will still exist hidden danger, that only in the syntax level required to provide more reliable safeguard, so say, strongly typed language code, the code reliable extent have obvious advantages, the use of a strongly typed language, you can eliminate the one most likely to exist in advance the type of the exception, We don’t have to wait until we’re in the middle of running and then go slowly half way.

Fifth, the advantage of strong type

    1. Bugs are exposed earlier: Eliminate most type problems during coding rather than waiting for bugs to be exposed during runtime
    1. The code is smarter, the code is more accurate
    • Weak typing actually doesn’t work as an intelligent hint for writing JavaScript, because there is no way for the developer to infer the type of the member;
    • Strongly typed language editor always knows the type of each variable, intelligent improvement can effectively improve the efficiency and accuracy of coding;
    1. Refactoring is more robust: Refactoring is a destructive change to the code, such as deleting an object member or changing its name
    • Weak typing: If you modify a method of an object member, but that method is referenced in another method, the modification is not notified until runtime. But strong typing will come up
    1. Reduce unnecessary type judgments
Function () {// If (typeof a! == 'number' || typeof b ! === 'numver') {throw new TypeError(' arguments must be numbers ')} return a + b}Copy the code

6. Overview of Flow

Flow is a static type checker for JavaScript. It is a feature introduced by Facebook in 2014. It can supplement the disadvantages of weak typing in JavaScript and provide a more complete type system for JavaScript. React and Vue use Flow.

Working principle: let us through the way of adding type annotations in the code, to mark code in what type of variables, parameters, and then the Flow according to the types of these annotations to check the code using exceptions, so as to realize the development phase to examine the abnormal types, this avoids back to now use of types of errors in operation stage;

For example:

Function sum(a, b) {return sum(a, b) {return sum(a, b) {return a + b} Return a + b} sum(100, 500) // ok sum(100, '20') // errorCopy the code

Additional type annotations in the code can be removed automatically before running through Babel or Flow’s official module, so they have no impact in production, and Flow does not require every variable to be annotated.

Flow is just a small tool with simple features to use

1. Get started quickly and use Flow

    1. Json: NPM init -y
    1. npm install -g yarn
    1. NPM install flow-bin //
    1. The file adds the tag @flow
    1. Yarn flow init // Initialize
    1. Yarn flow Running file
Function sum(a: number, b: number) {return a +b} sum(100, 100)Copy the code

2. Compile and remove type annotations

The code cannot execute the file using the Node command. If it executes, an error is reported.

  • Add flow-remove-types module:

    • Install yarn add flow-remove-types –dev
    • Run yarn flow-remove-types. -d dist (yarn flow-remove-types SRC / -d dist) //. Represents the current directory, dist represents the output path of JS files after removing comments;
  • Option 1: Add the build tool Babel + Preset -flow

    • yarn add @babel/core @babel/cli @babel/preset-flow –dev
    • .babelrc
          {
              "presets": ["@babel/preset-flow"]
          }
      Copy the code
    • yarn babel src -d dist

3. Develop tool plug-ins

Vscode plug-in:

More intuitive embodiment of code type exception problems: Flow language support; Notice that you don’t see type exceptions until you save them;

For other development tools, see the official Flow documentation

4. Flow type inference

According to the use of the code, to infer the type characteristics of variables is type inference, it is suggested to add type annotations in the code, so that the code has more readability; For example:

-flow will still find type errors. It will infer from the string we passed in the call that the n argument is a string and that string types cannot be multiplied; Function square (n) {// There is no type annotation here; return n*n } square(2)Copy the code

5. Annotation of Flow type

Add type annotations to restrict types more explicitly, and it will be helpful to understand the code later. Use type annotations if possible.

  • Type annotations canMark variables, function parameters, return value types

Function square(a: number) {return n*n} let num: function square(a: number) {return n*n} let num: Function foo() :number{} // Mark variable function foo() :number{} // mark returned value type function foo() :void{} // Add void if there is no return value typeCopy the code

6. Primitive type of Flow

For usage, use the flow command to check for type exceptions based on the type annotations added to the code.

What types Flow supports and more advanced usage

  • Primitive data type
const a: string = 'foobar' const b: number = NaN // NaN , Infinity const c: boolean = false; // true const d: NLL = null const e: void = undefined f: symbol = symbol ()Copy the code

7, Flow array type

Array types require generic parameters to express the type of each element in the array

Const arr1: Array<number> = [1,2,3] Number [] = [1,2,3] // an array of all numbers // a fixed length array called a tuple, foo has two types: string, number, number const foo: [string, number] = ['foo', 100]Copy the code

8. Flow object type

const obj1: {foo: string, bar: number} = { foo: 'string', bar: 100}// The current variable must have two members of foo and bar, which are of type string and number. Const obj2: {foo? : string, bar: number} ={bar: 100} // Use const obj3 ={} obj3.key1 = 'value1' obj3.key2 = 100 Const obj4 ={[string]: const obj4 ={[string]: String} = {} // Does not limit the number of members of this object, but limits the member type obj3.key1 = 'value1' obj3.key2 = 100Copy the code

9, Flow function type

General constraints on function parameters and function return values;

Function foo(callback (string,number)=>number){ Return number callback('string',100)} foo(function(STR,n){return n})Copy the code

10, Flow special type

  • Literal types:
    • The limiting variable must be a certain value;
    • Cooperate with union type usage;
    • Can be used in common types
    • The type keyword declares a single type and is used to indicate the result of a combination of multiple types
// The limit variable must be a value; Const a: 'foo' = 'foo' // with union type const type: 'success' | 'warning' | 'danger' = 'success' / / can be used in ordinary variable const b: String | number = 'string' / / 100, now has a string type, can also be a number/type / / type keywords separate type declarations, declared a type, Used to represent multiple type joint after the results of the type StringOrNumber = string | number / / said can use string, number const b: StringOrNumber = 'string'Copy the code
  • Maybe(?) There may be
Const gender: number = null // can't be null if necessary; You can add? Before number. const gender: ? Number = null / / said can accept null, undefined equivalent to the const gender: number | null | void = is undefinedCopy the code

11, Flow Mixed & Any

  • Mixed/Any: Accepts Any type of value
  • Differences: Any is a weak type, Mixed is a strong type
function passMixed(value: {value. Substr (1) value * value} passMixed('string') passMixed(100) function passAny(value: {value. Substr (1) value * value} passAny('string') passAny(100)Copy the code

12. Flow runtime environment API

Flow documentation: www.saltycrane.com/cheat-sheet…

JavaScript does not work in isolation. It must run in a specific environment, such as the browser environment, node environment, etc. Runtime environment must provide API use, browser environment: DOM, BOM;

Seven, TypeScript

TypeScript concepts

TypeScript is a programming language on top of JavaScript, a superset or extension of JavaScript. In fact, JavaScript is based on the original extension features, more is a set of more powerfulThe type system, as well as toSupport for new ECMAScript featuresThat will eventually compile toThe original Javascript;With TypeScript, developers can directly use the new features of TypeScript and its more powerful type system. After development, they can compile the code into JavaScript code that can be run directly in production environments.Avoid type anomalies in the development process, improve the coding efficiency, the reliability of the code;

TypeScript is eventually compiled into JavaScript, which is supported by any JavaScript runtime environment; For example: traditional browser, Node environment; TypeScript is a complete programming language that is more powerful and has a more robust ecosystem. Especially friendly to development tools;

Angular/ vuejs. 3 also starts using TypeScrip alternative flows

Typescript is a second language in the front-end domain; If it’s a small project that needs flexibility, it’s JavaScript itself. Use Typescript for long projects.

Typescript's disadvantages:

  • Disadvantage 1: The language itself has many more concepts, such as interfaces, enumerations, generics, etc., which raise the cost of learning; FortunatelyTypescript is progressive.;
    • Progressive meaning: Even if we don’t know any features, we can immediately write TypeScript code in JavaScript’s standard syntax, use it as JavaScript, and then use each feature as we learn it.
  • Cons 2: TypeScript is expensive early in the project because there are a lot of type declarations written for objects and functions. If it is a long-term maintenance of large projects, many times is once and for all;

Get started with TypeScript quickly

    1. Yarn init — yes // Initialize the manage package.json project
    1. Yarn add typescript –dev // a./bin/tsc file appears
    1. Yarn TSC file name // Run the file, TSC compiles the TS file, checks for types, removes annotations, and checks for new TypeScript features
Const hello = (name: string) => {console.log(' Helo ${name} ')} hello(100) // errorCopy the code

TypeScript configuration files

    1. Create tscconfig.json file, yarn TSC –init
    • Target: The standard used by compiled JavaScript
    • Module: commomJs/requireJs output code is modularized
    • outDir: “dist”; The folder to which the compiled results are output
    • RootDir: ‘SRC’; The folder where the source code (typescript) is located
    • sourceMap: true; It is easier to enable source mapping and then debug the typescript code using only sourceMap source files
    • strict: true; Turn on all strict check options
    1. Run the TSC project: YARN TSC

TypeScript raw data types

// Const a: string = 'foobar' const b: number = 100 const c: Boolean = true const d: Json file: strictNullChecks: false const e: void = undefined const f: null = null const g: undefined = undefined const h: symbol = Symbol()Copy the code

4. TypeScript standard library declarations

Symbol is TypeScript’s built-in object type;

The standard library is the declaration corresponding to the built-in object, use the built-in object must reference the corresponding standard library otherwise cannot find the corresponding type, will report an error;

TypeScript Chinese error messages

TypeScript supports multilingual development Settings; Mandatory English: yarn TSC — locale zh-cn;

Vscode error message: Open typescript locale-> zh-cn

TypeScript scope issues

Set to different features in different files, so that in this case, different files encounter the same name phenomenon;

  • Solution:
    • Use immediate execution functions;
    • Use modularity: export {}, because each module has its own input scope;
01.ts ---------------------------- const a: Number = 100 Error 02. Ts -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- const a number = 123 = = > modify / / use the immediate execution function (function () {123} const a number =) () / / Use modularity: export {};Copy the code

7. TypeScript Object types

The TypeScript Object type doesn’t just refer to ordinary Object types. Instead, it refers to all non-primitive types: objects, arrays, functions

Const foo: object =[]/ function() {}/{} const foo: object =[]/ function() {}/{} / const obj: {obj: number} = {foo:123}Copy the code

TypeScript array types

  • First type: generic Array<>
  • Second: element type []
Const arr1: Array<number> = [1,23,4] const arr2: number[] = [1,23,3]Copy the code

TypeScript tuple types

Special data deconstruction, in fact, is clear the length of the number of data, clear data type

  • To access an element of a tuple:
    • Const name = tuple[0] const name = tuple[0]
    • Const [name, age] = tuple
  • Typically used to return multiple return values in a function
Const tuple: [number, string] = [18, 'ax'] // Access an element of the tuple const name = tuple[0] const [name, age] = tupleCopy the code

TypeScript enumeration types

In the process of application development, some numerical values are often used to represent some states.

  • Characteristics of enumeration
    • A set of numerical names can be given more comprehensible names
    • There are only fixed values in an enumeration, and there is no possibility of going out of range
    • Enumeration types run in intrusive codeEventually compiled as a bidirectional key-value pair object
Enum PostStatus {Draft = 0, Unpublished =1, Published = 2 // If Draft = 0, Unpublished =1, Published = 2 } constt post = {title: 'hello', content: 'TypeScript is a typed superset', // status:2 // what state the numbers are corresponding to, often mixed with some other values (except the number 2) status: poststatus.draft}Copy the code

TypeScript function types

Restrict the input and output of a function

  • Functions can be expressed in two ways
    • Function declaration
    • Functional expression
Function func1(a: number, b? : number, ... rest: number[]): string { // ... Return 'func1'} func1(100, 100) const func2 = function (a: number, b? : number): // If you pass a function as an argument, you must restrict the type of the argument to the callback function. What type of return 'func2'} can be accepted using arrow functionsCopy the code

TypeScript any type

Because Javascript is weakly typed, many built-in apis accept arbitrary arguments, and TypeScript is built on top of Javascript. It is inevitable to accept arbitrary types of data in your code

Function stringify(vaue: any) {return json.stringify (value)} // Any is still a dynamic type; Let foo: any = 'string' foo = 100 foo.bar()Copy the code

TypeScript implicit type inference

In typescript, variable types are not explicitly annotated; they are inferred based on their use, called implicit type inference

Age = 'string'; let age=18; age= 'string'; let foo foo = 100 foo = 'string'Copy the code

TypeScript type assertions

There are special cases where TypeScript can’t infer the specific type of a variable, and we, as developers, are aware of the code; For example,

  • The way type assertions are made: the types of auxiliary code members. Type assertions are not type conversions, which are run concepts, and type assertions are compiled concepts
    • Use the key as
    • Use the < >
Const nums = [100,112,113] // The return value must be a number. They think they might not find it. Find (I => I >0) // const square = res * res // use key as const num1 = res As number // explicitly tells typeScript to say number // uses <>. When we use JSX in our code, JSX tags conflict const num2 = <number>resCopy the code

TypeScript interfaces

A specification, a contract, the deconstruction of a convention object, the use of an interface, must follow all the conventions of the interface. One of the most intuitive forms of typescript is to specify which members an object should have and their types.

Interface Post {title: string Content: string subtitile? Readonly summary: string // Read-only member} function printPost(post: Post) { console.log(post.title) console.log(post.content) } printPost({title: 'hello', content: 'A JavaScript'}) //Copy the code

Conclusion: Interface is used to constrain the deconstruction of objects, an object to implement an interface, it must have all the members of its constraints

  • Interface convention members:
    • Optional members: examples above
    • Read-only member: cannot be modified again
  • Dynamic members:
[key] interface Cache {[prop: string]: String} const cashe:Cache = {} cache.foo = 'value' // You can add any member, but the type must be stringCopy the code

13, TypeScript

Purpose: Describe the abstract features of a concrete object, such as a mobile phone

Abstract members used to describe a class of concrete objects; ES6 used to implement classes through function + prototype simulation. ES6 started with Class. Class syntax is enhanced in typescript;

  • In typescript, a class attribute must have an initial value or be assigned a value in a constructor. In addition, add some methods according to the ES6 standard
  • Class access modifiers:
    • Private can only be accessed internally
    • The public of the public
    • Protected Members that are protected and accessible only to subclasses
    • Readonly Read-only and cannot be modified.Can only be initialized by constructors/ Type declaration is initialized by =You only need one of the two
Public name: string = 'init name' private age: number = 18 // protected gender: Boolean // In typescript class attributes must have an initial value or be assigned a value in the constructor. Purpose: Add constructor(name: sting, age: number) { this.name = name this.age = age } sayHi (msg: String) {console.log(' I am ${naem},${MSG} ') console.log(this.age)}} //constructor is set to private, Student cannot be accessed from outside, Class Student extends Person() {private constructor(name: string, age: constructor); Number) {super(name, age) console.log(this.gender)} static create (name: string, age: Numer) {return new Student(name, age)}} const Tom = new Person(' Tom ', 18) console.log(tom.age) Create ('jack', 18) // ok const jack1 = new Student('jack', 18) // Error constructor is set to privateCopy the code

TypeScript classes and interfaces

Example: mobile phone is a type, examples are able to call, send text messages, the characteristics of mobile phone is enough to call, send text messages, but the phone is not only mobile phone, the more common landline can also call, but the landline does not belong to the class of mobile phone, because you can not send text messages, can not carry around; So if I use interface abstraction for these common features, it makes sense that I can make a phone call on my cell phone, I can make a phone call on my landline phone, because they implement the same protocol, and this protocol is called an interface class: abstract features that describe a specific class of things interface: common features use

  • Implements an interface implementation class using implements,
  • An interface constrains only one capability
Interface Eat() {Eat(food: string): {Eat(food: string) {Eat(food: string): Void} interface Run() {Run(distance: number): void} // class Person implements Eat,Run {Eat (food: string): Void {console.log(' Elegant dining: ${food} ')} run(distance: string): void{console.log(' Vertical walking: ${distance} ')}} // Animal class implements Eat,Run {Eat (food: string): void{console.log(' para.log ') ${food} ')} run(distance: string): void{console.log(' crawl: ${food} ')}}Copy the code

TypeScript abstract classes

A constraint subclass must have a member, but an abstract class can contain concrete implementation methods, unlike an interface, which contains only the abstraction of a member, but no concrete implementation

  • Abstract methods also do not require a method body.
  • The parent class is defined as abstract, and the subclass must implement the abstract method body
  • When you create an object using a subclass, you have both the parent class’s methods and its own methods

General categories: use abstract classes, such as animals; It’s a general term, it’s not specific, there’s a specific category underneath it

Abstract class: key child abstract is added before the class name

Abstract class Animal {eat(food: string): eat(food: string): Void {console.log(' console.log: ${food} ')} abstract run(distance: string): Void} // class Dog extends Animal{run(distance: string): void{console.log(' crawl: ${short} `)}} const d = new Dog () d.e ats (' mango) d.r UN (100).Copy the code

TypeScript generics<T>

When we define functions and interfaces and classes, we do not define specific types. When we use them, we specify specific types. (A generic is a function that is declared without specifying a type and called with a specific type. The purpose is to reuse code to a great extent.)

  • Generics: use<T>
  • Turn a type we can’t define into a parameter that we can pass when we use it
// Only one number type can be accepted; fucntion createNumberArray(length: number, value: number): Number [] {// Create an Array of any type, specify the element type, Const arr = Array<number>(legnth).fill(value) return arr} const res = createNumberArray(3,100) // res => Fucntion createNumberArray<T>(Length: number, value: T): T[] {const arr = Array<T>(legnth).fill(value) return arr} Const res = createNumberArray<string>('3','100')Copy the code

TypeScript type declarations

In real development, we use third-party modules. NMP modules are not necessarily written in typescript, so they don’t provide a strongly typed experience.

Summary: TypeScript references third-party modules. If the module does not contain a type declaration file, we try to install the corresponding declaration module. Normally the module is declared: @types/ module name. If there is no corresponding module name, you can only declare the corresponding type using the declare statement

// Use lodash // when we import, we start to report an error. We can't find the file with the type declaration. Solution: Install type declaration module // type declaration module: Import {camelCase} from 'lodash' import {camelCase} from 'lodash' import {camelCase} from 'lodash' import {camelCase} from 'lodash' import {camelCase} from 'lodash'; // Declare fucntion camelCase(input: string): string const res = camelCase(' hello typed ')Copy the code