1. The TypeScript

  1. TS for short, TypeScript is a superset of JavaScript. JS has all TS. JS code can run in TS environment. As shown below:

  1. On top of JS, add JSType of support. TypeScript =Type + JavaScript
// TypeScript code has explicit data types
let age1: number = 18
// The JavaScript code has no explicit type
let age2 = 18
Copy the code
  1. TypeScript is an open source programming language developed by Microsoft that runs anywhere JavaScript is running

  2. TypeScript is essentially no different from JavaScript; we can think of TypeScipt as JavaScript with type annotations that provide compile-time type safety for JavaScript code.

In fact, TypeScript is an “intermediate language” because it is ultimately converted to JavaScript for the browser to interpret and execute. TypeScript doesn’t break JavaScript’s architecture, however, it just extends it, as shown in the following figure:

2. Why add type support for JS?

1. Take a look at the defects of JS first

  • JS type system is weak, without the concept of type, when our code is overmuch, may on the way to a piece of code when our initial data type is changed, no type checking, caused when using JS for project development, will be the question of the wrong type, increased to find bugs, bugs instead of time, Seriously affect the development efficiency

The following code:

let arr = 11  // The initial value is of type number

arr = []  // Change the array type secretly

arr.toFixed(2) // There is a type error
Copy the code
  • JavaScript is dynamically typed, and errors are only discovered at run time.

2. TS belongs toStatically typed programming languages

  • It compiles and then executes. It cannot be executed directly, but must be compiled into JS to execute
  • 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

3. Experience the TypeScript

1. Install and compile the TS tool package globally

Installation package: NPM i-g typescript

Typescript package: a package that compiles TS code, provides TSC, and verifies that TS -> JS is successfully installed: TSC -v (see typescript version)

2. Install the ts – node

NPM i-g TS-node uses ts-Node packages to execute TS code directly in Node.js (no need to compile into JS files using TSC). It provides the ts-node command:

Ts – node files. Ts

3. Create a tsconfig.json file

TSC –init generates the configuration file tsconfig.json

After execution, a tsconfig.json file appears in the project root directory containing the configuration items for TS (which may vary slightly depending on the version).

{
  "compilerOptions": {
    "target": "es5".// Specify ECMAScript target version: 'ES5'
    "module": "commonjs".// Specify the module to use: 'commonJS ',' AMD ', 'system', 'umd' or 'es2015'
    "moduleResolution": "node".// Select the module resolution policy
    "experimentalDecorators": true.// Enable experimental ES decorator
    "allowSyntheticDefaultImports": true.// Allow default imports from modules that do not have default exports set.
    "sourceMap": true.// When compiling ts files into js files, generate the corresponding map file
    "strict": true.// Enable all strict type checking options
    "noImplicitAny": true.// There is an error with an implied any type on expressions and declarations
    "alwaysStrict": true.// Check modules in strict mode and add 'use strict' to each file
    "declaration": true.// Generate the corresponding.d.ts file
    "removeComments": true.// Delete all comments after compilation
    "noImplicitReturns": true.// Not all return paths of the function have return value error
    "importHelpers": true.// Import helper functions from tslib
    "lib": ["es6"."dom"].// Specify the library file to be included in the build
    "typeRoots": ["node_modules/@types"]."outDir": "./dist"."rootDir": "./src"
  },
  "include": [                              // ts files to compile * indicates file matching ** indicates ignoring file depth issues
    "./src/**/*.ts"]."exclude": [				    // No ts files need to be compiled
    "node_modules"."dist"."**/*.test.ts"]}Copy the code

3.TS annotations

background

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

This displays the format that flags unexpected behavior in the code, thus reducing the likelihood of errors:

Let variable name: type = initial value

Example:

Let name: string = ‘give me a div’

In this code, the type of the variable name is string, so we can only assign the value of the type to the variable. Otherwise, we will fail

Error code:


// Error: Assigned a value of type number to a variable of type string
let name: string = 8023
Copy the code

4. 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
// The type of the age variable is automatically inferred to be: number
let age = 18

// The type returned by the function is automatically inferred to be: number
function add(num1: number, num2: number) {
  return num1 + num2
}
Copy the code

5. The type of TS

1. Common basic types

The common base types in TS are divided into two categories

JS existing types

1. The original type: ` number/string, Boolean/null/undefined symbol ` 0. Object type: 'object' (array, object, function, etc.)Copy the code

TS New type

1. Union type 2. Custom type (type alias) 3. Interface 4. Tuples 5. literal types 6. enumerations 7. void 8. any, etcCopy the code
  • 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

2. Primitive types

  • Original type:number / string / boolean /null / undefined / symbol
  • Features: Simple, these types, written exactly according to the name of the type in JS
// A numeric type
let age: number = 10
// A string of characters
let myName: string = 'Give me a div.'
// Boolean type
let isLoading: boolean = false
// undefined
let un: undefined = undefined
// null
let timer:null = null
Copy the code

3. Association type

1. Union type format:

Let variables: type type 1 | 2 | 3… = the initial value

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

// Associative types: Array elements can be of one of two types
let arr: (number|string|boolean)[] = [1.2.3]

arr[0] = '1'
arr[2] = true
Copy the code

4. Array types

1. Two types of arrays can be written:

Let variable: type [] = [value 1…

Let variable: Array< type > = [value 1,…

2. Basic examples

//
let numbers: number[] = [1.3.5] // numbers must be arrays, and each element must be a number

//
let strings: Array<string> = ['a'.'b'.'c'] // Strings must be an array, and each element must be a string
Copy the code

3. Advanced usage

How to define an array whose elements can be string or numeric. (Combine union types to define arrays)

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

5. Type aliases

Format:

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

Type Alias = type

Use:

type s = string | number The type alias s can be either number or string

const str :s = 'Give me a div.'
const age :s = 10

// Define the type alias MyArr as an array type and the elements in the array can be numbers, characters, or Boolean values
type MyArr = (number | string) []
const arr:MyArr = [1.'1' , true]
Copy the code

6. Function types

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

1. The format:

Common function

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 => {}

Example 2.

// Function declaration
function add(num1: number, num2: number) :number {
  return num1 + num2
}

// Arrow function
const sub = (num1: number, num2: number): number= > {
  returnNum1 - num2} add (1.'1') / / an error
Copy the code

3. Simplified examples

The above code has the same parameter type and return value type. The code looks bloated and cumbersome, simplified as follows:

// Extract custom types using type aliases
type Fn = (n1:number,n2:number) = >number 
const add1 : Fn = (a , b) = > {return a + b }
const sub : Fn = (a , b) = > {return a - b }
Copy the code

7. The function returns void

1. The void type

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

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

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

  • Don’t write the return
  • Write return, but not followed by anything
  • Write the return undefined
// If nothing is written, add returns a value of type: void inference
const add = () = > {}
// The return type of the function is void
const add = (): void= > {}

If the return type is undefined, return undefined must be displayed in the function body
const add = (): undefined= > {
  // Undefined is returned as a value in JS
  return undefined
}
Copy the code

8. Functions – Optional and default arguments

Function parameters are optional. How do you define the types of these optional parameters?

1. The format

Add? After the optional parameter name.

Here the start and end arguments are defined as optional parameter types and must be numeric if passed, or notfunction 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

2. Default parameters:

End is the default. The default value is 10 and the type is number. After adding the default value, end becomes optional

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

3. The default and optional parameters are different

Similarities: When calling a function, it can realize the difference of less parameter transmission: After setting the default value, it is optional. If you do not write, the default value will be used. Optional does not have to have a value.

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: Optional and default parameters cannot be used together! ! !

9. Object types

1.object

In JavaScript, object is a reference type that stores a reference to a value. In TypeScript, we use this type when we want the type of a variable or function parameter to be an object:

let obj: object
obj = { name: 'TypeScript' }
obj = 123             // Error cannot assign type 123 to type object
console.log(obj.name) // Attribute 'name' does not exist on error type 'object'Copy the codeCopy the code

As you can see, an error is reported when an object is assigned to a variable of an object type. Object types are more suitable for the following scenarios:

function getKeys (obj: object) {
  return Object.keys(obj) // The values in obj are returned as a list
}
getKeys({ a: 'a' }) // ['a']
getKeys(123)        // Parameters of error type 123 cannot be assigned to parameters of type object
Copy the code

2. Object type – Used separately

  1. use{}To describe the object structure
  2. Attributes usedAttribute name: typeIn the form of
  3. Methods theMethod name (): return value typeIn the form of
  4. Optional attribute use?
// Create a type alias
type Person = {
  name: string,age: number,
  hobby? :string []    // Hobby is optional
  sayHi(): void
}

// Use a type alias as the type of the object: The optional hobby property does not declare that the page will not report errors
let person: Person = {
  name: 'Give me a div.'.age: 18
  sayHi(){}}Copy the code

3. Object type – Interface

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

  1. Type aliases:Type
  2. Interface:interface

format

Interface Interface name {Attribute 1: type 1, attribute 2: type 2,}

Example:

interface IGoodItem  {
    name: string, price: number, func: () = >string
}


const good1: IGoodItem = {
    name: 'watch'.price: 200.func: function() {
        return 'Watch the time'}}const good2: IGoodItem = {
    name: 'mobile phone'.price: 2000.func: function() {
        return 'Call'}}Copy the code

Description:

  1. useinterfaceKeyword to declare the interface
  2. Interface name, such as hereIPerson), can be any valid variable name, recommendedIAt 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

4. Interface inheritance

Background:

interface Point2D { x: number; y: number }

interface Point3D { x: number; y: number; z: number }

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

Interface inheritance:

interface Point2D { x: number; y: number }
/ / Point2D inheritance
interface Point3D extends Point2D {
  z: number
}
Copy the code
  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).

10. Tuples Tuple

There is no concept of tuples in JavaScript. As a dynamically typed language, it has the advantage of supporting arrays of elements of multiple types. But for extensibility, readability, and stability, we usually stuff different types of values into an object as key-value pairs and then return the object, rather than using arrays with no limits at all. TypeScript's tuple types complement this, making it possible to define arrays that contain a fixed number of elements, each of which may not be of the same typeCopy the code

A tuple can be seen as an extension of an array, representing an array with a known number and type of elements. It is particularly suitable for multi-valued returns. We know the type of the element at each position in the array, and we can assign the element to the tuple index:

let arr: [string, number, boolean];
arr = ["a".2.false]; // There are no errors
arr = [2."a".false]; // Error cannot assign type "number" to type "string". Type "string" cannot be assigned to type "number".
arr = ["a".2];        // error Property '2' is missing in type '[string, number]' but required in type '[string, number, boolean]'
arr[1] = 123
Copy the code

Description: Tuple types mark exactly how many elements there are and the type of each element

11. Literal types

Let’s start with the following code:

let str1 = 'Hello give me a div' // The type is string

const str2 = 'Hello give me a div'  // The type is :hello give me a div
Copy the code

explain

  1. Str1 is a variable (let) whose value can be any string, so the type is:string
  2. Str2 is a const, it can’t change but ‘hello give me a div’, so it’s of type ‘Hello give me a div’

Any JS literal (e.g., object, number, etc.) can be used as a type, where ‘hello give me a div’ is a literal type, meaning that a particular string can also be used as a type in TS

Let STR: ‘hello’ = ‘hello’ is equivalent to const STR = ‘hello’

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

// Use custom types:
type Dir = 'up' | 'down' | 'left' | 'right'

function changeDirection(direction: Dir) {
  console.log(direction)
}

// When calling a function, write ", and there is a type prompt: the argument passed must be one of the above optional values
changeDirection('up')
Copy the code

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