Working people! For the soul! It’s the front end! This series is recorded in the learning process of pull hook education big front end training camp. If there is something wrong in the article, we hope you can criticize and correct it, and make progress together. Please indicate the source of reprint.

Language type

Type safety

  • Strongly typed

At the language level, the argument types of functions must be the same as the parameter types, and arbitrary implicit type conversions are not allowed.

  • Weak type

Weak types do not restrict the type of arguments, allowing arbitrary implicit type conversions.

funciton sum(a, b) {
    console.log(a + b)
}
sum(1.2)  / / print 3
sum(1.'a') / / print 1 a
Copy the code

The type system

  • The static type

When a variable is declared, its type is unambiguous; after it is declared, its type cannot be changed.

  • Dynamic type

The type of a variable can be changed at any time, and only the runtime can determine the type of a variable. A variable has no type, and the value stored in a variable is typed.

var a 
a = 'hello'
console.log(a)  // hello
a = 123
console.log(a)  / / 123
Copy the code

Problems with JavaScript’s own type system

With the strong and weak typing, dynamic and static typing, we can see that JavaScript is weakly typed and dynamically typed. This is because early applications written in JavaScript were relatively simple and had no compilation. Similar to the above example, we write a sum function that adds two numbers. We just want to add two numbers, but if we input a string, the result will be a string concatenation. This is the problem with weak typing, making our code unreliable and unable to detect problems in time.

The advantage of strong typing

  • Mistakes are exposed earlier
  • The code is more accurate, the code is smarter
  • Refactoring is more reliable
  • Reduce unnecessary type judgments

TypeScript basis

What is TypeScript?

TypeScript is a free, open source programming language developed by Microsoft. It is a superset of JavaScript that essentially adds optional static typing and class-based object-oriented programming to the language. It is supported by any JavaScript runtime environment, and TypeScript offers the latest and evolving JavaScript features that are more powerful, robust, and complete.

Disadvantages:

  • Early in the project, using TypeScript adds costs.
  • The language itself has some new concepts relative to JavaScript, which increases the cost of learning.

But TypeScript is progressive, and we use JavaScript syntax to get started with TypeScript.

At the beginning of the TypeScript experience

Install the TypeScript

npm install -g typescript
Copy the code

The configuration file

Generate the configuration file tsconfig.json

tsc --init
Copy the code

// Common configuration options in the generated configuration file
// target => The compile target is ES5
// lib => library declaration, here we reference ES2015, DOM, ES2017
// outDir => Directory for storing compiled files
// rootDir => File root path
Copy the code

Compile TypeScript files

// The TSC command can be used directly after the tsconfig.json file is configured
tsc

// If we don't have the tsconfig.json file configured
tsc xxx.ts
// will give us xxx.js
Copy the code

Scope problem

In TypeScript, members in files are treated as global members by default, and conflicts occur if there are multiple identical members in multiple files.

Solutions:

  1. Use IIFE to provide independent scope
(function () {
    const a = 123} ())Copy the code
  1. Use export on the current file, which turns the current file into a module with a separate scope.
const a = 123
export {}
Copy the code

Basic data types

Primitive data type

The basic types are string, number, Boolean, null, undefined, Symbol, void.

const str:string = 'string'
const num:number = 1
const boo:boolean = true
const n:null = null
const u:undefined = undefined
const s:Symbol = Symbol(a)const v:void = undefined
Copy the code

The Object type

Object refers to any type other than the original data type

const fun:object = function () {}

const obj:{name:string, age:number} = {
    name : 'xm'.age : 25
}
Copy the code

Array type

// 1. An array of elements of this type can be represented by [] after the element type
let arr : number[] = [1.2.3]
// 2. Array generics can also be used
let arr : Array<number> = [1.2.3]
Copy the code

Tuples Tuple

A meta-ancestor type represents an array with a specified number and type of elements.

let arr : [string, number] = ['xm'.20]
Copy the code

Enumeration Enum

Using enumerations, we can define some names with clarity, express intent or create a differentiated set of use cases. Divided into numeric enumeration and string enumeration.

Digital enumeration
enum Direction {
    Up = 1,
    Down,
    Left,
    Right
}
// The initial value of Up is 1, and the remaining members automatically grow from 1. Down = 2, Left = 3, Right = 4
Copy the code
String enumeration

String enumerations have no self-growing behavior, but they serialize nicely.

enum Direction {
    Up = "UP",
    Down = "DOWN",
    Left = "LEFT",
    Right = "RIGHT",}Copy the code

Function types

We can type the return value of a function

function sum(a: number, b: number) :number {
    return a + b
}
sum(1.2)
Sum = sum; sum = sum; sum = sum; sum = sum
Copy the code
Optional and default parameters

In TypeScript we can use it next to parameter names, right? Implement optional parameter function, optional parameter and default parameter must be followed must be last

// This parameter is optional
function buildName(firstName: string, lastName? : string) {
    if (lastName)
        return firstName + "" + lastName;
    else
        return firstName;
}

// Default parameters
function buildName(firstName: string, lastName:string = "xm") {
    // ...
}
Copy the code

Any type

Any type can also be weakly typed, meaning any type can be.

let foo: any = 'string'
foo = 100
foo.bar()
Copy the code

Implicit type conversion

Implicit type conversions exist in TypeScript, so it is recommended that we add an explicit type to each variable.

let age = 18   // number
age = 'string' / / an error

let foo        // Do not declare the type
foo = 100      // Defaults to any type
foo = 'string' / / is not an error
Copy the code

Types of assertions

Type assertions are like conversions in other languages, but without special data checking or deconstruction, they have no run-time impact and only work at compile time. It’s like we tell TypeScript, trust me, I know what type this variable is, I know what I’m doing.

// Assume that the NUMS comes from an explicit interface
const nums = [110.120.119.112]
const res = nums.find(i= > i > 0)
const square = res * res / / here will be an error, because the TypeScript uncertain what types of res, const res: number | undefined

Using type assertions is the same in both ways
const num1 = res as number
const num2 = <number>res  // This mode cannot be used under JSX
Copy the code

Interface interface

Define some structure that we must follow in order to use the interface.

interface Post {
  title: stringcontent? :string  / /? Represents an optional member
  readonlys summary: string // Read-only attribute
}

function printPost (post: Post) {
  console.log(post.title)
  console.log(post.content)
}

printPost({
  title: 'Hello TypeScript'.content: 'A javascript superset'./ / is optional
  summary: 'hello'  // Read-only cannot be modified
})

// Dynamic member
interface Cache {
  [prop: string] :string 
}

const cache: Cache = {}

cache.foo = 'value1'
cache.bar = 'value2'
Copy the code

Class class

class Person {
    // Class attributes need to be explicitly declared for use
    name: string
    age: number
    
    constructor (name: string, age: number) {
        this.name = name
        this.age = age
    }
	sayHi (msy: string): void {
        console.log(I was `The ${this.name}.${msg}`)}}Copy the code

Class access modifier

  • Default: public Public property
  • Private is a private property and cannot be accessed externally
  • Protected, much like private, is not externally accessible, but is accessible in derived classes
  • Readonly Read-only property
  • Constructors can also be made private and protected
class Person {
    private name: string
    protected readonly age: number
    
    constructor (name: string, age: number) {
        this.name = name
        this.age = age
    }
	sayHi (msy: string) :void {
        console.log(I was `The ${this.name}.${msg}`)}}Copy the code

Classes and interfaces

interface Eat {
    eat(foot: string) :void
}
interface Run {
    run(distance: number) :void
}
class Person implements Eat.Run {
    eat(food: string) :void {

    }
    run(distance: number) :void{}}class Animal implements Eat {
    eat(food: string) :void{}}Copy the code

An abstract class

Abstract classes are used as base classes for other derived classes. They are generally not instantiated directly. Unlike interfaces, abstract classes can contain implementation details of members. The abstract keyword is used to define abstract classes and abstract methods within abstract classes.

abstract class Animal {
    abstract makeSound(): void;
    move(): void {
        console.log('roaming the earch... ');
    }
    // An abstract method in an abstract class contains no concrete implementation and must be implemented in a derived class
    abstract run (distance: number) :void
}
Copy the code

The generic

function createNumberArray(length: number, value: number) :number[] {
    const arr = Array<number>(length).fill(value)
    return arr
}
// This function can only create arrays of numbers. If we want to create arrays of strings, we need to write another function
function createArray<T> (length: number, value: T) :T[] {
    const arr = Array<T>(length).fill(value)
    return arr
}
const res = createNumberArray(3.100)
const numArr = createArray(3.'you')
const strArr = createArray(3.100)
Copy the code

Type declaration

import { camelCase } from 'lodash'

declare function camelCase (input: string) :string

const res = camelCase('hello typed') // Can also be usednpm install @types/lodash --devAdd a type declaration moduleCopy the code

History article portal

  • Big front – end approach (a) functional programming
  • Big front – end approach (two)JavaScript asynchronous programming
  • Hand write promises
  • New ECMAScript features

reference

Pull hook big front end training camp