An overview of the
TypeScript is a superset of JavaScript (extension set) : includes JavaScript/type system/ES6+; It eventually compiles to Javascript;
Advantages:
- TypeScript is supported in any JavaScript runtime environment;
- TypeScript is much more powerful and ecologically sound than Flow;
- TypeScript alerts you to type errors as you write them, without requiring additional commands or plug-ins to check for them.
Disadvantages:
- The language itself adds many concepts: interfaces/generics/enumerations… , increase the cost of learning;
- TypeScript adds costs early in the project, such as defining declarations of classes, models, interfaces, etc.
Quick learning
Installation:
// Initialize package yarn init --yes // install TypeScript dependency yarn add TypeScript --devCopy the code
// TypeScript can write code in full JavaScript standard syntax;
const helloTypeScript = (name: Number) => { console.log('hello' + name) } helloTypeScript('world!! ') // Arguments of error type "string" cannot be assigned to arguments of type "Number". helloTypeScript(100) // successCopy the code
The configuration file
Command line configuration:
yarn tsc --init // Successfully created a tsconfig.json file
Copy the code
tsconfig.json:
{"target": "es5", // module": "commonJS ", // output "sourceMap": True, "outDir": "dist", // Output folder "rootDir": "./", // ts files in the current directory "strict": true, // In strict mode, no undeclared type is allowed}}Copy the code
Run the command:
yarn tsc
Copy the code
The original type
Const a: string = 'test' const b: number = 100 const c: Boolean = true // "strict": Under the false, the string | number | Boolean type can be null or undefined const d: Boolean = undefined const e: void = undefined const f: null = null const g: undefined = undefinedCopy the code
Standard library declaration
The standard library is the declaration file for the built-in objects.
Tsconfig. json declares the standard library as “target”: “ES5 “, so when using ES6 objects in the program, for example: Symbol type:
Const h:symbol = symbol () // error: "symbol" refers only to the type, but is used here as a value. Do you need to change the target library? Try changing the 'lib' compiler option to ES2015 // or later.Copy the code
Json: “target: “es2015”; Or add lib:
"lib": ["ES2015"],
Copy the code
Set Chinese error messages
VS Code Settings => Search => typescript locale switch language; Default is NULL, with whom the editor system is set
The Object type
Types in Typescript refer not only to ordinary object types, but to arrays, objects, and functions in general. Define common object types with {}:
/ / const object type foo: object = {} | | [] | | () = > {} / / / / {} object types Can use object literal way, better way for interface to define a const object foo: { name: string, age: number } = { foo: 123, bar: 'string' }Copy the code
Array type
- Generics:
Array<T>
- Element type:
T[]
Const arr1: Array<number> = [1, 2, 3] const arr2: number[] = [1, 2, 3] // an instance const sum = (... args: number[]): number => args.reduce((prev, current) => prev, current, 0) console.log(sum(1, 2, 3, 'a')) // args TypeErrorCopy the code
A tuple type
A tuple is an array with an explicit number and an explicit element type:
const tuple: [number, string] = [18, 'age'] // true
// Type '[number, string, number]' is not assignable to type '[number, string]'.Source has 3 element(s) // but target allows only 2
const tuple: [number, string] = [18, 'age', 20]
// Type 'number' is not assignable to type 'string'.
const tuple: [number, string] = [18, 20]
Copy the code
Purpose: Tuples can be used to return multiple return values in a function.
Enumerated type
Certain values represent certain states, which have two characteristics:
- Give a set of numbers a better-understood name;
- There are only a few fixed values in an enumeration and no possibility of going out of range;
Traditional definition variables:
Const activeStatus = {START: 1, FINISHED: 2, ENDING: 3} const activeInfo = {id: 10000, name: '1 ', status: Activeinfo. status === Activestatus. START // The activity has started activeInfo.status === Activestatus. FINISHED // The activity is complete Activeinfo. status === ActiveStatus.ENDING // The activity has endedCopy the code
Enumeration type definitions:
Enum ActiveStatus {START = 0, FINISHED, ENDING} const activeInfo = {id: 10000, name: '1 ', status: 1 } console.log(activeInfo.status === ActiveStatus.START) // false console.log(activeInfo.status === ActiveStatus.FINISHED) // trueCopy the code
Enumeration values are compiled into the compiled code, affecting the compiled results, which look like this:
var ActiveStatus; (function (ActiveStatus) { ActiveStatus[ActiveStatus["START"] = 0] = "START"; ActiveStatus[ActiveStatus["FINISHED"] = 1] = "FINISHED"; ActiveStatus[ActiveStatus["ENDING"] = 2] = "ENDING"; })(ActiveStatus || (ActiveStatus = {})); Var activeInfo = {id: 10000, name: 'active ', status: 1}; console.log(activeInfo.status === ActiveStatus.FINISHED);Copy the code
Constant enumerations, compiled without intruding into compiled code, are commented out:
// const enum ActiveStatus {START = 0, FINISHED, ENDING} console.log(activeInfo.status === activestata.start); console.log(activeInfo.status === ActiveStatus.FINISHED); Var activeInfo = {id: 10000, name: 'active ', status: 1}; console.log(activeInfo.status === 0 /* START */); // false console.log(activeInfo.status === 1 /* FINISHED */); // trueCopy the code
Function types
Function type constraints are mainly type restrictions on the input (arguments) and output (return values) of a function:
JavaScript has two ways of defining functions:
- Function declaration
Function fun1(a: number, b: number): string { return 'hellow' + a + b } fun1(10, 10) // true fun1(10) // false fun1(100, Function fun2(a: number, b: number, c? : string): string { return 'hellow' + a + b + c } fun2(100, 10) // true fun2(100, 10, 'world') // true fun2(100, 10, Function fun3(a: number, b: number, c: string = 'world'): function fun3(a: number, b: number, c: string = 'world') string { return 'hellow' + a + b + c }Copy the code
When setting optional parameters, ignore? Syntax and default syntax must come last; If multiple optional parameters exist, set them one by one.
- Functional expression
We need to define the types of function input and output:
const fun3: (a: number, b: number, c? : string, d? : string) => string = function (a: number, b: number, c: string = 'world') { return 'hellow' + a + b + c }Copy the code
Types of assertions
In some cases, TypeScript can’t assert the specific type of a variable, but you can use type assertions to tell TypeScript what type a variable will be if you know the type of the variable.
For example, the server returns a set of data representing the student’s grade information, and now needs to filter out the specific grade information:
Const data = [100, 200, 300] const findRst = data.find(res => res > 1) // filter: Number | | undefined / / assertions as keywords const assertFilter = findRst as number / / assertions with < > const assertFilter2 = < number > findRst // In JSX, <> may conflict with labels and is not recommendedCopy the code
Note: Type assertion is just a way to assist TypeScript with type inference, it is not a type conversion; Type conversions are a run-time concept, and type assertions occur only at compiler compile time;
Interface Interfaces
Interfaces can be understood as a specification or contract. They are abstract concepts that constrain the structure of objects. To use an interface, we must follow all the conventions of that interface.
In TypeScript, interfaces are used to specify which members need to be defined in object properties. And what those member types are;
Interface Post {title: string; Function printPost(post: Post) {console.log(post.title) console.log(post.content)} printPost({title: 'name', content: 'hello' })Copy the code
Members of the special usage: set the optional | read-only idiom | | multi-type members dynamic type
interface Post { title: string content: string desc? : string/members/optional readonly summary: the string / / read-only member id cannot be changed after setup: string | number / / g/prop: string: } const postObj = {title: 'name', content: 'hello'}Copy the code
Basic use of class
Class to describe abstract characteristics of concrete transactions; Abstract members used to describe a class of concrete objects;
TypeScript enhances the syntax for classes. Unlike ES6 classes, in TypeScript, class properties cannot be defined directly in constructors. Instead, they must be declared and typed before being initialized in constructors.
Such as:
class Person {
name: string
age: string
constructor (name: string, age: number) {
this.name = name
this.age = age
}
}
Copy the code
Special usage – access modifier private: private | public: open | protected: protected, including:
private
: Attributes defined can only be accessed within the class, not by instancepublic
The default property in: class is publicprotected
: Cannot be obtained by instance, andprivate
The difference is that in addition to being accessed within the class, it is also available in subclasses:
Such as:
class Person {
name: string
age: number
protected gender: boolean
constructor (name: string, age: number) {
this.name = name
this.age = age
this.gender = true
}
}
class Children extends Person {
constructor(name: string, age: number) {
super(name, age)
console.log(this.gender) // true
}
}
Copy the code
Special note: When constructor is set to private, the class cannot be instantiated or inherited. Instantiation of this class can only be instantiated internally by defining static methods:
class Student extends Children {
static of(name: string, age: number) {
return new Student(name, age)
}
private constructor(name: string, age: number) {
super(name, age)
console.log(this.gender) // true
}
}
const newStudent = Student.of('lelei', 9) // true
Copy the code
Class read-only property: readonly. When an attribute of a class already has an access modifier, readOnly can be followed only by the attribute modifier:
class Student extends Children {
public readonly name: string
protected readonly age: number
}
Copy the code
Classes and interfaces
Different classes have some characteristics in common with each other. For these common features, we generally use interfaces to abstract them:
Example demonstration:
Class Person {eat(food: string): void {console.log(' For the enjoyment of food, eat: '+ food)} run(distance: number): distance }} Animal {eat(food: string): Animal {eat(food: string): Void {console.log(' to eat: '+ food)} run(distance: number): void {console.log(' crawl '+ distance)}}Copy the code
Above, two classes Person and Animal are defined. They both have the ability to eat and run, but their abilities are different. Typically we will implement capability inheritance and constraints by defining superclass inheritance for multiple classes that have the same capability and capability implementation. For classes that have the same capabilities but implement different capabilities, we constrain common capabilities across multiple types by defining interfaces.
Interfaces are defined only to constrain function types, not methods, and best practice is to constrain only one capability per interface:
interface Eat {
eat(food: string): void
}
interface Run {
run(distance: number): void
}
Copy the code
Implements the interface using the implements keyword
Class Persons implements Eat, Run{Eat (food: string): void {console.log(' to enjoy the pleasure of eating: '+ food)} Run (distance: Number): void {console.log(' to walk: '+ distance)}} class Animal implements Eat, Run (food: string): Void {console.log(' to eat: '+ food)} run(distance: number): void {console.log(' crawl '+ distance)}}Copy the code
An abstract class
Abstract classes are somewhat like interfaces, used to constrain the presence of certain members in a subclass. Unlike interfaces, which are only abstractions of members and do not contain member concrete implementations, abstract classes can contain concrete implementations.
For large classes (just a generalization of large, not a specific subdivision type), use abstract classes:
Way to define abstract classes: Use the abstract keyword, which precedes the class. Once defined as an abstract class, the class can only be inherited, not instantiated. To instantiate an abstract class, you must define subclasses to inherit from the parent class and then instantiate the child class.
Eat (food: string): eat(food: string): Void {console.log(' baa baa, ${food} ')} // We can define abstract methods that constrain methods of the same class in subclasses. Abstract methods do not require a method body. Class Dog extends Animal {run(distance: number): Implemented: void {// throw new Error("Method not implemented.") console.log(' implemented ', ${distance} ')}} // Instantiate const smallDog = new Dog() console.log(smalldog.eat (' fish ')) console.log(smalldog.run (100))Copy the code
The generic
Generics: When defining a function or interface or class, an implementation of the type is specified only when it is used.
Purpose: maximum reuse of code;
Example:
Function createNumberArray(Length: number, value: number): Number [] {return Array<number>(length).fill(value)} function createStringArray(length: number, value: string): string[] { return Array<string>(length).fill(value) }Copy the code
Generic implementation: use the keyword T to specify parameters whose class type is indeterminate, for example:
Function createArray<T> (length: number, value: T): T[] { return Array<T>(length).fill(value) } // function createArray(length: number, value: unknown): unknown[] createArray() // function createArray<string>(length: number, value: string): string[] createArray<string>(5, 'test') // function createArray(length: number, value: unknown): unknown[] createArray<boolean>(5, true)Copy the code
Interface:
interface ParsedQuery<T = string> {
[key: string]: T | T[] | null;
}
Copy the code
The general idea of a generic is to turn an undefined type into a parameter, and then specify and pass that parameter when used.
Type declaration
When a function/interface does not declare its type when it is defined, but wants to declare its type when it is used, it can declare a type statement using the keyword declare:
declare function doSomething(prams: Type): Type
Copy the code
When using third-party plug-ins that don’t support TypeScript, try installing a version of TypeScript: @type/ XXX