TypeScript

The type of programming language

  • Dynamically typed language
    • Do not declare data types
  • Statically typed language
    • Data types need to be declared

Static versus dynamic typing

What exactly is TypeScript

  • JavaScript that scales
  • Statically typed style type system
  • Syntax support from ES6 to ES10 and even ESNext
  • Compatible with all browsers, all kinds of systems, all kinds of servers, completely open source

Why use TypeScript

1. The program is easier to understand

  • Problem: parameter types of input and output of functions or methods, external conditions, etc
  • Dynamic language constraints: procedures such as manual debugging are required
  • With TypeScript: the code itself answers the appeal question

2. Be more efficient

  • Jump between different code quickies and definitions
  • Automatic code completion
  • Rich interface tips

3. Fewer mistakes

  • Most errors can be found during compilation
  • Eliminate some common mistakes

4. Very inclusive

  • Fully compatible with JavaScript
  • Third-party libraries can write type files separately
  • Most projects support TypeScript

3. Environment construction

1. Install

npm install typescript -g
tsc -V
Copy the code

2. Run

// convert ts to js
tsc demo.ts
/ / js
tsc demo.js
Copy the code
npm install -g ts-node
// Execute ts directly
ts-node demo.ts
Copy the code

Basic grammar

1. Raw data type and Any type

The data type

Undefined and null

let isDone: boolean = false;

let firstName: string = 'viking';
let message: string = `Hello, ${ firstName }`;

let age: number = 10;

let u: undefined = undefined;
let n: null = null;

let num: number = undefined;

let Person: {
  name: string.age: number
} = {
  name: 'kstring'.age: 19
}
Copy the code

The ts type cannot be assigned to another type, otherwise an error will be reported

any

Any type, can arbitrarily call methods, attributes and assign values to other types, lose the role of type checking, there is a clear type is not recommended to use, in order to avoid causing unnecessary errors

let notSure: any = 4;
notSure = 'string';
notSure = true;

notSure.myName;
notSure.getName();
Copy the code

2. Arrays and tuples

let arrOfNumbers: number[] = [1.2.3];
Copy the code

Tuple: An array of limited data types

// No more or less elements
let user: [string, number] = ['kstring'.19];

// Have array methods, but can only add the type defined in the tuple, otherwise an error will be reported
user.push('king'); // [ 'kstring', 20, 'king' ]
user.shift(); // [ 20, 'kstring' ]

// A two-dimensional tuple
const teacherList: [string, string, number][] = [
  ['dell'.'male'.19],
  ['sun'.'female'.26],
  ['jen'.'fem'.38]]Copy the code

3. Interface Interface

  • Describes the shape of an object

  • Duck Typing

    • A strategy for object type inference that focuses more on how objects are used than on the objects themselves
// Define the interface
interface Person {
  // Read-only attribute
  readonly id: number,
  name: string,
  // Optional attribute,age? : number, }let Person: Person = {
  id: 2.name: 'kstring'.age: 19,}Copy the code

4. The Function Function

  • In JS, functions are first-class citizens
    • You can store it in an array, either as a parameter or as a return value
// Can not participate in the determination of parameters after the optional parameters, unlike the optional attributes of the object
const add = (x: number.y: number, z? :number) :number= > {
  if (z) {
    return x + y + z;
  }
  return x + y;
}
// Note that => is declaring the return value type, not the arrow function in ES6
let add2: (x: number, y: number, z) = > number = add
Copy the code

Object type annotation

function add ({ x, y }: { x: number, y: number }) {
  return x + y;
}
add({ x: 1.y: 2 });
Copy the code

Note: in ts :\color{#FF0000}{:}: are all declaration types, independent of code logic

Interface: describes the function

interface ISum {
  // Define the return value as:, not =>
  (x: number.y: number, z): number
}

let add2: ISum = add
Copy the code

5. Type inference, joint types, type assertions, and type aliases

5.1 Type inference

Type inference: Automatically deduce worthy types

5.2 Union Types

Union type: Multiple types can be specified, but only the specified type can be assigned

let numberOrString: number | string
Copy the code

5.3 Type Assertion

Type assertion: A type that can be used to manually specify a value

function getLength(input: string | number) :number {
	const str = input as string;
    if (str.length) {
    	return str.length;
    } else {
    	const number = input as number;
        return number.toString().length
    }
}
Copy the code
function getLength(input: string | number) :number {
    if ((<string>input).length) {
        return (<string>input).length;  
    } else{}}Copy the code

5.4 Type Aliases

Type alias: A type alias gives a type a new name. Type aliases are sometimes similar to interfaces, but can work with primitive values, union types, tuples, and any other type you need to write by hand

type Name = string;
Copy the code
function sum(x: number, y: number) :number {
    return x + y;
}

const sum2: (x: number, y: number) = > number = sum;

type: PlusType = (x: number, y: number) = > number;

const sum3 = PlusType;
Copy the code

6. class

  • Class: Defines the abstract characteristics of everything
  • Object: An instance of a class
  • Object Oriented (OOP) three major features: encapsulation, inheritance, polymorphism

Access type

  • Public: The modified property or method is common and allowed to be used both inside and outside the class
  • Protected: Decorated properties or methods are protected and allowed to be used within a class and in inherited subclasses
  • Private: Modified properties or methods are private and allowed to be used within the class
  • Abstract: abstract
  • Readonly: indicates the read-only property

6.1 packaging

  • Hide method details, provide only external interface, meaning protection or prevent code (data) from being inadvertently destroyed, encapsulation principle high cohesion, low coupling
    • Cohesion: Cohesion refers to the degree to which parts within a module are related to each other
    • Coupling: Coupling refers to the degree of connection between modules
class Animal {
  // Private attributes
  private sum:number = 0;

  getSum():number {
    return this.sum;
  }

  setSum(sum) {
    this.sum = sum; }}Copy the code

6.2 inheritance

  • Inheritance: A subclass may inherit the characteristics of its parent class
    • Improve code reuse
class Animal {
 name: string;
 
 constructor(name) {
   this.name = name;
 }

 run() {
   return this.name; }}class Dog extends Animal {
 bark() {
   return `The ${this.name} is barking`}}const tantan = new Dog('tantan');

console.log(tantan.run()); // tantan 
console.log(tantan.bark()); // tantan is barking
Copy the code

6.3 polymorphic

  • Polymorphism: Different states occur when different objects perform the same behavior.
    • For example: the meow of a cat, the meow of a dog, both are meow, but they make different sounds
    • Improved code extensibility
class Animal {
  cry() {
    console.log("Call"); }}class Dog extends Animal {
  cry() {
    console.log("Wang wang"); }}class Cat extends Animal {
  cry() {
    console.log("Meow"); }}const animal = new Animal();
const dog = new Dog();
const cat = new Cat();

animal.cry(); / / call
dog.cry(); / / wang wang
cat.cry(); / / meow meow
Copy the code

6.4 the abstract class

The purpose of an abstract class is to implement parts common to multiple subclasses without having to write to the implementation class repeatedly

Abstract classes cannot be instantiated, only inherited

abstract class Geom {
	abstract getArea(): number;
}
Copy the code

6.5 Similarities and Differences between Abstract Classes and interfaces

The same

  1. Can’t be instantiated
  2. Can contain abstract methods. These abstract methods are used to describe the services that the system can provide, but do not necessarily provide a concrete implementation
  3. Interfaces and abstract classes are data types

The difference between

  1. You can provide default implementations for partial methods in an abstract class, eliminating the need to implement them repeatedly. Improved code reusability. This is the advantage of abstract classes
  2. A class can only inherit from a direct parent (which may be an abstract class). However, a class can implement multiple interfaces, which is an advantage of interfaces

7. Classes and interfaces

  • Inheritance dilemma
    • A subclass can have only one parent
  • Classes can use implements to implement interfaces, which can be implemented in multiple ways
/ / on the radio
interface Radio {
  switchRadio(trigger: boolean): void;
}

/ / battery
interface Battery {
  checkBatteryStatus(): void;
}

/ / motor vehicles
class Car implements Radio {
  switchRadio(trigger: boolean){}}/ / cell phone
class Cellphone implements Radio.Battery {  
  switchRadio(trigger: boolean) {

  }

  checkBatteryStatus(): void{}}Copy the code

8. The enumeration enums

Wikipedia: In mathematical and computer science theory, an enumeration of a set is a program that lists all the members of some finite set of sequences, or a count of objects of a particular type. The two types often (but not always) overlap. [1] is a set of named integer constants. Enumerations are common in daily life, such as SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY.

Using enumerated types allows us to define constants with names, express intent clearly, or create a differentiated set of use cases. In TypeScript, numeric and string-based enumerations are supported. Enumerations complement the JS standard data types by declaring a set of named constants within a range of constants, such as Monday through Friday,

Examples of TypeScript enumerations are recommended

enum Direction {
  Up,
  Down,
  Left,
  Right
}

console.log(Direction.Up); / / 0
console.log(Direction[0]); // Up
Copy the code

A const in front of an enumeration can reduce overhead

cosnt enum Direction {
  Up,
  Down,
  Left,
  Right
}
Copy the code

9. The generic generics

Generics: Parameterization of types by passing them as method parameters

function echo<T> (arg: T) :T {
	return arg;
}

// The Boolean passed in returns a Boolean value
const result = echo(true)
Copy the code
function swap<T.U> (tuple: [T, U]) :U.T] {
  return [tuple[1], tuple[0]];
}

const result2 = swap(['string'.123]);
Copy the code

10. Constrain generics

interface IWithLength {
	length: number
}

// The constraint pass parameter must have a length attribute
function echoWithLength<T extends IWithLength> (arg: T) :T {
  console.log(arg.length);
  return arg;
}

const str = echoWithLength('string');
const obj = echoWithLength({ length: 20 });
const arr = echoWithLength([1.2.3]);
// echoWithLength(13) // error
Copy the code

11. Use of generics in classes and interfaces

Class:

class Queue<T> {
  private data = [];
  
  push(item: T) {
    return this.data.push(item);
  }

  pop(): T {
    return this.data.shift(); }}const queue = new Queue<number>();
queue.push(1);
console.log(queue.pop().toFixed());
Copy the code

Interface:

interface KeyPair<T, U> {
    key: T,
    value: U
}

let kp1: KeyPair<number, string> = { 
    key: 1.value: 2
}

let arr: number[] = [1.2.3];
let arrTwo: Array<number> = [1.2.3]
Copy the code

12. Declaration documents

TypeScript is a superset of JavaScript, and its most critical feature is static Type Guard. However, JavaScript itself does not have static type checking, and the TypeScript compiler provides only library type declarations in the ECMAScript standard, which recognize only types in TypeScript code. So for some third libraries you need declaration files that end with.d.ts.

Most third-party libraries have their own declaration files, which do not need to be written by themselves

npm install --save jquery
// Jquery declaration file
npm install --save @types/jquery
Copy the code

JQuery Declaration file