Introduce TypeScript

  • TS Official Documentation
  • TS 英 文 reference – No more maintenance

What is the TypeScript

TS is a superset of JS

  1. TS for short, TypeScript is a superset of JavaScript. JS has all TS. JS code can run in TS environment.
  2. On top of JS, add JSType of support. TypeScript =Type + JavaScript
  3. TypeScript isMicrosoftAn open source programming language developed to run anywhere JavaScript is running
// TypeScript code has an explicit data type let age1: number = 18 // JavaScript code has no explicit data type let age2 = 18Copy the code

Why add type support for JS?

The defect of JS

  1. The JS type system is weakly typed and has no concept of type

    Let ar = 11 // let ar = [] // let ar = 11 // let ar = [Copy the code

    There is no type verification, resulting in the use of JS project development, will often encounter the problem of type error, increase the time to find bugs, Bug correction, seriously affect the development efficiency

  2. JavaScript is a dynamically typed programming language

    Explain as you execute, and errors can only be found at run time.

TS is a statically typed programming language

  1. It compiles and then executes. It cannot be executed directly, but must be compiled into JS to execute
  2. It does type checking at compile time to catch errors ahead of time. With VSCode and other development tools, TS can find the type errors in the code in advance when writing the code, reducing the time to find bugs and fix bugs

Contrast:

  • Use JS:

    1. Write code in VSCode
    2. Run the code in the browser –> run time, the error will be found [evening]
  • TS:

    1. When writing code in VSCode –> while writing code, errors will be found.
    2. Run the code in the browser

    The difference between javascript and Typescript

  1. Ts is fully javascript compatible and can be compiled into javascript
  2. Using TS comes with powerful code type hints
  3. Improved code maintainability, making it easier to refactor code
  4. Support for the latest ECMAScript syntax..ts----- compile -->.js

ecological

Vue 3 source code is rewritten using TS, Angular supports TS by default, React works well with TS, and TypeScript has become the programming language of choice for medium to large front-end projects

Currently, the latest front-end development stack:

  1. React: TS + Hooks
  2. Vue: TS + Vue3

Note: Vue2 does not support TS well

Global installation of the TS compilation toolkit

Installation package: NPM i-g typescript

  • Typescript package: a package used to compile TS codetscCommand, the implementation of TS -> JS transformation
  • Verify that the installation is successful:TSC - v(Check the typescript version.)

Note: When installing global packages on macs, you need to add sudo access: sudo NPM i-g typescript

Compile and run the TS code

steps

  1. Create the js file. For example, the hello.ts file (note that the suffix of the ts file is.ts)

  2. Compilation. Compile TS to JS

    Type the command TSC hello.ts in the terminal (at this point, a JS file with the same name will appear in the same directory)

  3. Execute the JS code.

    1. Run in Node. Enter a command in the terminal,node hello.js
    2. Run it in a browser.

Ts-node simplifies running TS

The target

Understand the basic usage of the TS-node command.

Problem description

After each code change, you have to repeat two commands to run the TS code, which is tedious.

TSC your code. Ts node your code. JsCopy the code

Simplify the way

Using the TS-Node package, execute ts code directly in Node.js. It provides ts-Node commands to simplify command execution.

Install command

npm i -g ts-node

Ts equivalent to: 1 TSC command 2 node (note: ts-node does not generate JS files)

Explanation: the ts-node command internally steals ts- > JS and then runs the JS code

summary

During the initial learning phase, we will use TS-Node to run the code, but not during the project phase.

Ts-node reported an error. Procedure

Console. log reported an error

Cannot find name 'console'. Do you need to change your target library? Try changing thelibcompiler option to include 'dom'.

To solve

  1. tsc --initGenerate the configuration file tsconfig.json
  2. When writing code, wrap it with {}

TS annotations

TypeScript is a superset of JS. TS provides all the functionality of JS with the addition of a type system

  • TS definition variables (constants) can now specify types.
  • Variables of type A cannot hold data of type B

The display flags unexpected behavior in the code, reducing the likelihood of errors

Type annotations

format

Let variable name: type = initial valueCopy the code

Sample code:

let age: number = 18
Copy the code

Note: The: number in the code is a type annotation

Effect: Adds type constraint ** to a variable.

In the above code, the convention variable age is of type number, so the variable can only be assigned a value of that type. Otherwise, an error will be reported

Let age: number = '18' let age: number = '18'Copy the code

Type inference

In TS, the type inference mechanism of TS automatically provides the type in some cases where the type is not explicitly specified. Benefits: In some cases, type annotations can be omitted due to type corollary

There are two common scenarios in which type inference occurs

  1. Declare a variable and initialize it
  2. When determining the return value of a function
Number function add(num1: number, num2: number) { return num1 + num2 }Copy the code

The type of TS

Common base types

The common base types in TS are divided into two categories

  1. JS existing types

    1. Original type:number/string/boolean/null/undefined/symbol
    2. Object type:object(Including arrays, objects, functions, etc.)
  2. TS New type

    1. The joint type
    2. Custom types (type aliases)
    3. interface
    4. tuples
    5. Literal type
    6. The enumeration
    7. void
    8. Any etc.
  • Note:

    1. The original typeIt is written the same in TS and JS
    2. Object typeTS is even more verbose, with each concrete object (for example, arrays, objects, functions) having its own type syntax

The original type

  • Primitive types: number/string, Boolean/null/undefined symbol
  • Features: Simple, these types, written exactly according to the name of the type in JS
// Let age: number = 18 // string type let myName: string = 'little flower' // Boolean type let isLoading: boolean = false // undefined let un: undefined = undefined // null let timer:null = nullCopy the code

The joint type

demand

How do you define a variable that can be of type NULL or number?

Master the use of union types:

let arr: (number | string)[] = [1, 'a', 3, 'b']
Copy the code

The format of the union type

Let variables: type type 1 | 2 | 3... = the initial valueCopy the code

Explanation: | (vertical) in TS is called joint types, namely: consists of two or more other types of type, can be said one of these types

Application scenarios

  1. The timer id
/ / / / | joint type joint type 1: variables can be one of the two types of the let the timer: number | null = null timer = 2 / / joint type 2: array element can be one of two types of the let arr: (number | string | Boolean) [] = [1, 2, 3] arr [0] = '1' arr [2] = trueCopy the code

Note: this is the joint type of grammar, TS is only a vertical bar, don’t in JS or (| |) or confused

An array type

Two kinds of writing

format

Let variable: type [] = [value 1... Let variable: Array< type > = [value 1,...Copy the code

Basic example

// Let numbers: number[] = [1, 3, 5] // Let numbers: number Array<string> = ['a', 'b', 'c'] // strings must be arrays, and each element must be a stringCopy the code

Expand the sample

How to define an array whose elements can be string or numeric.

Analysis, used in conjunction with union types

let arr: (number | string) [] = ['1', 1]
Copy the code

There is a priority issue here

Type the alias

format

define

Type Alias = typeCopy the code

use

Const str1:s = 'ABC' const str2:string = 'ABC'Copy the code

role

  1. Alias the type
  2. A new type is defined

scenario

Alias complex types

// type NewType = string | number
​
// let a: NewType = 1
// let b: NewType = '1'
​
// let arr: NewType[] = [1, '1']
    
type MyArr = (number | string) []
const arr:MyArr = [1, '1']
​
Copy the code

An alias can be any legal string, usually with a capital letter

Function – single definition

The target

Conventions for the types involved in a function

Type of function

Function types actually refer to the types of function parameters and return values

format

// Common function function name (parameter 1: type = default, parameter 2: type = default): return value type {} // arrow function const function name (parameter 1: type = default, parameter 2: type = default): return value type => {}Copy the code

The sample

Function add(num1: number, num2: number): number {return num1 + num2} const add = (num1: number) Number =10, num2: number=20): number= > {return num1 + num2} add (1,'1'Copy the code

Function – Defines the function format uniformly

The problem

The code is cumbersome when defining multiple functions with the same parameter type and return value type

const add = (a:number,b:number):number =>{
        return a + b
    }
​
    const sub = (a:number,b:number):number =>{
        return a - b
    }
Copy the code

Analysis of the

Define functions that have the same parameters and arguments as a whole

const add1 : (n1:number,n2:number)=>number  =  (a,b)=>{return a+b }
Copy the code

Refine custom types

type Fn = (n1:number,n2:number) =>number 
const add1 : Fn = (a,b)=>{return a+b }
Copy the code

The function returns void

Void type

If the function does not return a value, the return type is void

function greet(name: string): void {
  console.log('Hello', name)
  //
}
Copy the code

If a function does not return a value, void should be used in the TS type

  • Don’t write the return
  • Write return, but not followed by anything
  • Write the return undefined
Void const add = () => {} // Void const add = () => {} Void => {} // Const add = (); const add = (); const add = (); Undefined => {// here, return undefined is a value in JS}Copy the code

Void and undefined

  1. If the function does not specify a return value, the value is undefined after the call

  2. When the return value is undefined cannot be declared directly

    Function add(a:number, b:number): undefined {console.log(a,b)}Copy the code

Function – Optional argument

scenario

When a function is used to implement a function, arguments may or may not be passed.

For example, the array slice method can be slice(), slice(1), or slice(1, 3)]. In this case, optional arguments are used when specifying types for function arguments

format

Optional: Add? To the end of the optional parameter name. (question mark)

function mySlice(start? : number, end? : number): void {console.log(' start index: ', start, 'end index: ', end)}Copy the code

Note: Optional parameters can only appear at the end of the parameter list, that is, optional parameters cannot be followed by mandatory parameters

The difference between optional and default values

Similarities: Fewer parameters can be passed when calling a function

Difference: After setting the default value, it is optional, do not write will use the default value; Optional does not have to have a value.

Note: They cannot be used together. The default value is preferred

Object type – Used separately

The target

Master the description of assigning a type to an object

format

Const object name: {Attribute name 1: type 1, attribute name 2: type 2, method name 1(parameter 1: type 1, parameter 2: type 2) : return value type, method name 2 (parameter 1: type 1, parameter 2: type 2)=> Return value type} = {attribute name 1: Value 1, attribute name 2: value 2}Copy the code

Optional properties with?

Const object name: {attribute name 1? : Type 1, attribute name 2: type 2} = {attribute name 2: value 2}Copy the code

The sample

Const goodItem:{name: string, price: number, func: ()=>string} = {name: 'phone ', price: 2000, func:function(){return 'call'}}Copy the code

Description:

  1. use{}To describe the object structure
  2. Attributes usedAttribute name: typeIf it’s multiple lines, you can omit it,
  3. Methods theMethod name (): return value typeIn the form of
  4. Optional use?

Object type – Type alias

The target

Use type aliases to simplify the way you define the type of an object

Train of thought

Encapsulate the type annotation to define the type

The sample

SayHi (): void} type Person = {name: string, age: number sayHi(): void} SayHi () {}} function f1 (p: Persion) :void {}Copy the code

summary

  1. Once you have created a type alias, you can simply use that type alias as a type annotation for the variable

Object type – Interface

The target

Master the use of interfaces

scenario

When an object type is used more than once, there are two ways to describe the object type for reuse purposes.

  1. Type alias, type
  2. Interface, the interface

format

Interface Interface name {Attribute 1: type 1, attribute 2: type 2,}Copy the code

The sample

Interface IGoodItem {name: string, price: number, func: ()=>string} const good1: IGoodItem = {name: 'watch ', price: 200, func: function() {return 'see time'}} const good2: IGoodItem = {name: 'phone ', price: 2000, func: function() {return' see time '}} const good2: IGoodItem = {name: 'phone ', price: 2000, func: Function () {return 'call'}}Copy the code

Explanation:

  1. useinterfaceKeyword to declare the interface
  2. The interface name (for example, IPerson in this case) can be any valid variable nameIAt the beginning
  3. After declaring the interface, use the interface name directly as the type of the variable

Interface and type differences

Interface vs. type alias:

  • Similarities: Both types can be assigned to objects

  • Difference:

    • Interface that can only be typed for objects. It can inherit.
    • Type aliases, which allow you to specify not only the type of an object, but virtually any type

Recommendation: Use type if you can use type

------------- interface IPerson {name: string, age: number} const user1: IPerson = {name: 'a', age: ------------- type Person = {name: string, age: number} const user2: Person = {name: 'b', age: 20}Copy the code

Interface inheritance

The target

Master interface inheritance

background

For example, if both interfaces have x and y attributes, write them twice, ok, but tedious

interface IPoint2D { x: number; y: number }
interface IPoint3D { x: number; y: number; z: number }
Copy the code

Analysis of the

If two interfaces have the same properties or methods, the common properties or methods can be separated and reused through inheritance

Inheritance format

Interface extends interface 1 {Property 1: type 1, // Special type of interface 2... }Copy the code

Examples of interface inheritance

interface Point2D { x: number; Y: number extends Point2D {z: number}Copy the code

Explanation:

  1. useextendsThe (inheritance) keyword implements interface Point3D to inherit Point2D
  2. When inherited, Point3D has all the attributes and methods of Point2D (at the same time, Point3D has x, Y, and Z attributes).

tuples

The target

Master the use of tuple types

scenario

Fixed structure of data, e.g

  • Use latitude and longitude coordinates to mark location information
  • Use x,y to record mouse position

You can use arrays to record coordinates

Let position: number[] = [116.2317, 39.5427] // Array elements are numeric typesCopy the code

The problem

Disadvantages of using number[] : it is not rigorous, because an array of this type can have any number of digits, like latitude and longitude, which can only have two digits.

Tuples Tuple

Tuples are another special kind of array:

  • Exactly how many elements it contains
  • The type corresponding to a particular index
Let position: [number, number] = [39.5427, 116.2317]Copy the code

Explanation:

  1. Tuple types mark out exactly how many elements there are and the type of each element
  2. In this example, the element has two elements, each of type number

The sample

The simulation defines useState.

The return value of useState is an array with number as the first element and a function to modify number as the second.

function useState(n: number): [number, (number)=>void] {
        const setN = (n1) => {
            n = n1
        }
        return [n, setN]
    }
​
const [num ,setNum] = useState(10)
Copy the code

Literal type

thinking

Let str1 = 'hello wuhan 'const str2 =' Hello Wuhan 'Copy the code

Q: What type is STR1? What type is STR2?

Through the TS type inference mechanism, the answer can be obtained:

  1. The variable str1 has type: string
  2. Str2 variable of type: ‘Hello TS’

explain

  1. Str1 is a variable (let) whose value can be any string, so the type is :string
  2. Str2 is a const, its value cannot be changed except ‘hello wuhan ‘, so its type is :’ Hello Wuhan ‘
  • Note: ‘Hello TS’ is a literal type, which means that a particular string can also be a type in TS

Literal type

Any JS literal (for example, objects, numbers, etc.) can be used as a type

Description:

  1. Let a above is equivalent to const
  2. Const a = ‘ABC’

{name: ‘jack’} [] 18 20 ‘ABC’ false function() {}

The function of literals

A single literal is of little use; it is commonly used with union types to represent an explicit list of optional values

Example 1

For example, in snake, the direction of the game can only be up, down, left, or right

/ / use the custom type: type Direction = 'up' | 'down' | 'left' | 'right' function changeDirection (Direction: {console.log(Direction)} // When calling a function, write '' and get a type message: changeDirection('up')Copy the code

Note: The parameter direction can only be up, Down, left, or right

Advantages: Using literal types is more precise and rigorous than using string types

Example 2

Actiontype in the story

type ActionType = 'ADD_TODO' | 'DEL_TODO'
function reducer(type:ActionType) {
  if(type === 'ADD_TODO')
}
Copy the code

Example 3

There can be only two genders

Let gender: 'girl' | 'boy' = 'boy' gender = 'ABC' / / an errorCopy the code

summary

Literal-type conventions: only certain values can be taken. Generally used with union types.