TypeScript is a programming language built on top of JavaScript that addresses JavaScript’s type system. TypeScript greatly improves the reliability of your code. TypeScript can write code in full JavaScript standard syntax.

The type system

JavaScript is a weakly typed and dynamically typed language that lacks the reliability of the type system.

Strong and weak types

By type safety, programming languages are classified as strongly typed and weakly typed.

Strongly typed: The language level restricts the argument types of functions to be the same as the parameter types.

Weak typing: The language level does not restrict the types of arguments.

Strongly typed languages do not allow arbitrary implicit type conversions, whereas weakly typed languages do.

Variable types are allowed to change at any time, not strong and weak type differences

Static and dynamic types

By type checking, programming languages are classified into static and dynamic types.

Static typing: when a variable is declared, its type is unambiguous; after it is declared, its type cannot be changed.

Dynamic typing: The type of a variable is known at run time, and it can change at any time.

A variable in a dynamically typed language has no type; the value stored in a variable is typed.

TypeScript is quick to get started

The installation

Install the installation using YARN

yarn add typescript --dev

use

Create a new 1.ts file

const hello = (name: any) =>  {
  console.log(`Hello, ${name}`)
}

hello('TypeScript')
Copy the code

Use yarn TSC 1.ts to compile.ts files into.js files. The added type annotations are removed

var hello = function (name) {
    console.log("Hello, " + name);
};
hello('TypeScript');
Copy the code

The configuration file

The TSC command can compile an entire project as well as a specified TS file. However, TypeScript configuration files are typically created before compiling the entire project.

You can create a tsconfig.json file using the yarn TSC –init command.

You can no longer use the TSC command to compile a particular TS file. The TSC command only works when you compile the entire project, and all ts files in the compiled project need to be in the SRC directory.

TypeScript raw data types

Const a: string = 'foobar' const b: number = 100 // NaN Infinity const c: Boolean = true // false // In strictNullChecks mode, string, number, Boolean can not be empty // in strictNullChecks mode, string, number, Boolean cannot be empty. Json file const d: string = null const d: number = null const d: E: void = undefined const f: void = undefined const f: void = undefined const f: void = undefined const f: void = undefined const f: void = undefined const f: void = undefined const f: null = null const g: // Symbol is a member of the ES2015 standard. ES2015 const h: symbol = symbol (); ES2015 const h: symbol = symbol ();Copy the code

Scope problem

Const a = 123 // Solution 1: Execute the function immediately, Const a = 123 export {} function () {const a = 123 export {} function () {const a = 123 export {} function () {const a = 123 export {}Copy the code

The Object type

Object in TypeScript refers not only to ordinary Object types, but to all non-primitive types, namely Object, Array, and Function.

// The Object type export {} // make sure there are no member conflicts with other examples // The Object type refers to a type other than the original const foo: Const obj: {foo: number, bar: string } = { foo: 123, bar: 'string' }Copy the code

An array type

Const arr1: Array<number> = [1, 2, 3] const arr2: Array<number> = [1, 2, 3] Number [] = [1, 2, 3] / / case -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- / / if the JS, you need to determine whether each member is the number/TS/use, type of guaranteed, don't add type judgment, You can add type annotations function sum (... args: number[]) { return args.reduce((prev, current) => prev + current, 0) } sum(1, 2, 3) // => 6Copy the code

A tuple type

A tuple is an array with an explicit number of elements and each element type. Each element type need not be identical.

// make sure there is no member conflict with other examples const Tuple: [number, string] = [18, Const name = tuple[1] const age = tuple[0] const name = tuple[1] name] = tuple const entries: [string, number][] = Object.entries({ foo: 123, bar: 456 }) const [key, value] = entries[0] // key => foo, value => 123Copy the code

Enumerated type

Enumerated types have two characteristics:

  1. You can give asynchronous values separate names that are easy to understand
  2. There are only a few fixed values in an enumeration, and there is no possibility of going out of range

There are no enumerated values in JavaScript.

// Enumeration (Enum) export {} // Make sure there are no member conflicts with other examples // Enumeration with objects const PostStatus = {Draft: 0, Unpublished: 1, Published: 2} // Standard enumeration enum enum PostStatus {Draft = 0, Unpublished = 1, Published = 2} Enum PostStatus {Draft = 6, Unpublished, // => 7 Published // => 8} // String enumeration, Enum PostStatus {Draft = 'aaa', Unpublished = 'BBB ', Published =' CCC '} // Enumeration types invade runtime code, This will affect the compiled results. // Most types are eventually removed after compilation and conversion, just for type checking during compilation. // Enumerations are eventually compiled into a bidirectional key-value object. // Bidirectional key-value objects can get values by keys. Enum PostStatus {Draft = 'aaa', Unpublished = 'BBB ', Published = 'CCC'} PostStatus[0] // => Draft // const enum PostStatus {Draft, Unpublished, Published}Copy the code

Function types

// Function type export {} // make sure there are no member conflicts with other examples // Function parameters must have exactly the same number of arguments, i.e., the number of parameters is equal to the number of arguments // Optional arguments can be used if an argument is required. Or use the parameter defaults. Function func1 (a: number, b: number = 10,... Rest: Number []): string {return 'func1'} func1(100, 200) func1(100, 200, 300) const func2: (a: number, b: number) => string = function (a: number, b: number): string { return 'func2' }Copy the code

Any type

Export {} // make sure there are no member conflicts with other examples any) { return JSON.stringify(value) } stringify('string') stringify(100) stringify(true) let foo: Any = 'string' foo = 100 foo.bar() // The any type is unsafeCopy the code

Implicit type inference

If TypeScript does not explicitly annotate the type of a variable through type annotations, TypeScript will infer the type of the variable based on its usage, a feature called implicit type inference.

Let age = 18 // number age = 'string'// Because TypeScript already extrapolate age to number // If TypeScript can't infer what type the variable is, Let foo foo = 100 foo = 'string' // It is recommended to add an explicit type notation for each variableCopy the code

Types of assertions

Type assertions help TypeScript make the type of each member in your code more explicit.

A type assertion is not a conversion; it does not convert one type to another. Type conversions are concepts at runtime, whereas type assertions are concepts at compile time, after which the code is compiled.

Const nums = [110, 120, 119, const nums = [110, 120, 119, const nums = [110, 120, 119, 112] const res = nums.find(I => I > 0) // As and const num1 = res as number Const num2 = <number>res // Cannot be used under JSXCopy the code

interface

Interface is an abstract concept that can be used to define the structure of an object. When we use an interface, we must follow all the conventions of the interface.

// interface Post {title: string content: string } function printPost (post: Post) { console.log(post.title) console.log(post.content) } printPost({ title: 'Hello TypeScript', content: 'A javascript superset'}) // Optional member, read-only member, dynamic member export {} // Make sure there are no member conflicts with other examples interface Post {title: string content: string subtitle? : string // use? } const hello: Post = {title: {title: {title: {title: {title: {title: {title: {title:} 'Hello TypeScript', content: 'A javascript superset', summary: 'A javascript' } interface Cache { [prop: string]: String // Dynamic member} const cache: cache = {} cache.foo = 'value1' cache.bar = 'value2'Copy the code

class

Classes can be used to describe abstract features of a concrete class of things.

// Class (Class) export {} // Make sure there are no member conflicts with other examples Class Person {// Public name: string private age: Protected readonly gender: Boolean // Private attributes, not accessible externally, inheritance allowed. // Constructor (name: string, age: Number) {this.name = name this.age = age this.gender = true} // sayHi (MSG: string): void { console.log(`I am ${this.name}, ${msg}`) console.log(this.age) } } class Student extends Preson{ constructor(name: string, age: Number){super(name, age) console.log(this.gender)// print true}} const Tom = new Person('Tom', 18) console.log(tom.name)// Output Tom console.log(tom.age)// error console.log(tom.gender)// Error // Class and interface export {} // Interface Eat {Eat (food: string): void} interface Run {Run (distance: number): Class Person implements Eat, Run {Eat (food: string): void {console.log(' elegant eating: ${food} ')} run (distance: number) {console.log(' Walking: ${food} ')}} class Animal implements Eat, run {Eat (food: food) ${food} ')} run (distance: number) {console.log(' crawl: ${distance} ')}}Copy the code

Abstract classes can be used to constrain subclasses to have certain members, and can contain concrete implementations. Interfaces do not include concrete implementations.

Abstract class export {} // make sure there is no member conflict with other examples. Void {console.log(${food} ')} abstract run (distance: number): void } class Dog extends Animal { run(distance: number): Void {console.log(' quad ', distance)}} const d = new Dog() d.eat(' ummm ') d.run(100)Copy the code

The generic

Generics are the characteristic of defining an interface, function, or class without specifying a specific type until it is used.

Function createArray<T> (length:) function createArray<T> (length:) function createArray<T> number, value: T): T[] { const arr = Array<T>(length).fill(value) return arr } const res = createArray<string>(3, 'foo')Copy the code