TypeScript study notes

TypeScript study notes

1. TypeScript definition

TypeScript is a superset of JavaScript and extends the syntax of JavaScript. TypeScript provides static type checking at compile time through type annotations.

2. TypeScript basic types

2.1 Boolean type

//Assign variables directly after declaration let c: boolean = false; Copy code

If the variable declaration and assignment are carried out at the same time, ts can automatically check the type of the variable

let c = false; c = true; //c = 123; This line of code will report an error, because the type of the variable a is boolean, not an assignment number Copy code

2.2 Number type

let a:number; //The type of a is set to number, and the value of a can only be a number in the previous use process a = 10; //a ='hello';//This line of code will report an error, because the type of variable a is number, not an assignment string Copy code

2.3 String type

let b: string; b ='hello'; Copy code

2.4 Array type

let list: number[] = [1, 2, 3]; let list: Array<number> = [1, 2, 3];//Array<number> generic syntax Copy code

String[] represents an array of strings

let e1: string[]; e1 = ['a','b','c']; Copy code

2.5 tuple

tuple (tuple): is a fixed-length array syntax: [type, type, type]

let h: [string, number]; h = ['hello', 123]; Copy code

2.6 Enumeration

enum Gender{ Male = 0, Female = 1, } let i: {name: string, gender: Gender}; i = { name:'The Monkey King', gender: Gender.Male//'male' } console.log(i.gender === Gender.Male) Copy code

2.7 any type

Any represents any type. Setting the type of a variable to any is equivalent to turning off the type detection of TS for the variable. When TS is used, it is not recommended to use the any type

let d: any; copy the code

If you declare a variable without specifying a type, the TS parser will automatically determine that the type of the variable is any (implicit any)

let d; d = 10; d ='hello'; d ='true'; Copy code

When the type of d is any, it can be assigned to any variable

let d:any; let s:string; s = d; Copy code

2.8 Unknown type

let e: unknown; e = 10; e = true; e = "hello"; Copy code
  • unknown is actually a type-safe any
  • Variables of unknown type cannot be directly assigned to other variables
let s:string; //s = e;//Error: Cannot assign type "unknown" to type "string" if (typeof e === "string") { s = e; } Copy code

2.9 Void type

Void is used to represent empty, taking a function as an example, it means a function with no return value

function fn2(): void{ } Copy code

2.10 Never type

never: means that the result will never be returned; there is no value

function fn3(): never{ throw new Error("Reported an error!"); } Copy code

2.11 Null and Undefined types

In TypeScript, undefined and null have their own types, undefined and null respectively

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

2.12 object type

object represents a js object

let a:object; a = {}; a = function(){ }; Copy code
  • {} Is used to specify which attributes can be included in the object
  • Syntax: {attribute name: attribute value, attribute name: attribute value}
  • Add after the attribute name? , Indicating that the attribute is optional
let b: {name: string, age: number?}; copy the code

If there is no? after age, the first one below will report an error

b = {name:'stonet'}; b = {name: "Sun Wukong", age: 18}; Copy code

The following assignment will report an error; the object text can only specify known attributes, and "c" is not in the type"

let c3: {name: string, a?:number, b?:number}; c3 = {name:"Pig Bajie", a:1, b:2,c:3} Copy code

[propName: string]:any represents any type of property

let c: {name: string, [propName: string]:any} c = {name:"Pig Bajie", age: 18, gender:'Male'} Copy code

Set the type declaration of the function structure: Syntax: (formal parameter: type, formal parameter: type...) => return value

let d1: (a:number ,b: number)=>number; d1 = function (n1: number, n2: number): number { return n1 + n2 } Copy code

2.13 Type alias

type myType = 1 | 2 | 3 | 4 | 5; let k: myType; let l: myType; let m: myType; k = 2; m = 6;//Cannot assign type "6" to type "myType" Copy code

2.14 Type assertion

Type assertion: can be used to tell the parser the actual type syntax of the variable:

  1. Variable as type
let someValue: any = "this is a string"; let strLength: number = (someValue as string).length; Copy code
  1. <type> variable
let someValue: any = "this is a string"; let strLength: number = (<string>someValue).length; Copy code

2.15 Union type

You can use | to connect multiple types (joint types)

let b1: "male" | "female"; b1= "male"; b1= "female"; let c1: boolean | string; c1 = true; c1 ='hello'; Copy code

3. TypeScript class

3.1 Introduction to classes

Use the class keyword to define a class, the object mainly contains two parts: Attribute method

class Person{ /* The directly defined attributes are instance attributes and need to be accessed through the instance of the object; const per = new Person(); per.name The attribute at the beginning of static is a static attribute (type), which can be accessed directly through the class Person.age The attribute at the beginning of readonly indicates that a read-only attribute cannot be modified */ //Define instance attributes //name: string ='The Monkey King'; //readonly name: string ='The Monkey King'; name ='The Monkey King'; //Use the static keyword before the attribute to define the class attribute (static attribute) //static readonly age: number = 18; age = 18; //Define method /* If the method starts with static, the method is a class method, which can be called directly through the class */ sayHello(){ console.log("Hello everyone!") } } //new an instance const per = new Person(); console.log(per.name); per.name ='tom'; console.log(per.name) //console.log(Person.age);//Can be used when static //Person.sayHello(); per.sayHello(); Copy code

3.2 Constructor

class Dog { name: string; age: number; //constructor is called the constructor //The constructor will be called when the object is created constructor(name: string, age: number) { //In the instance method, this means the current instance //In the constructor, the current object is the newly created object //You can add properties to the newly created object through this //console.log(this); this.name = name, this.age = age } bark(){ alrt('barking!!!'); console.log(this.name); } } const dog = new Dog(' ', 4); const dog2 = new Dog(' ', 2); //const dog3 = new Dog();//should have 2 parameters, but got 0 //const dog4 = new Dog(); console.log(dog); console.log(dog2); //console.log(dog3); //console.log(dog4); dog.bark(); Copy code

3.3 Inheritance

(function (){ //Define an Animal class class Animal{ name: string; age: number; constructor(name: string, age: number){ this.name = name; this.age = age; } sayHello(){ console.log('Animals are calling!!'); } } /* Dog extends Animal -At this time, Animal is called the parent class and Dog is called the child class -After using inheritance, the child class will have all the methods and properties of the parent class -Through inheritance, the code shared by multiple classes can be written in a parent class, This only needs to be written once to make all subclasses have the properties and methods in the parent class at the same time -If the same method as the parent class is added to the subclass, the subclass method will override the parent class method This form of subclasses overriding the methods of the parent class is called rewriting */ //Define a class that represents a dog //Make the Dog class inherit the Animal class class Dog extends Animal{ //name: string; //age: number; //constructor(name: string, age: number){ //this.name = name; //this.age = age; //} //sayHello(){ //console.log('barking!!'); //} run(){ console.log(`${this.name} is running~~`); } sayHello(){ console.log('Wow!!'); } } //Define a cat class //Make the Cat class inherit the Animal class class Cat extends Animal{ //name: string; //age: number; //constructor(name: string, age: number){ //this.name = name; //this.age = age; //} //sayHello(){ //console.log('Meow meow!!'); //} sayHello(){ console.log('Meow meow meow!!'); } } const dog = new Dog('Wang Cai', 5); const cat = new Cat('Mimi', 3); console.log(dog); dog.sayHello(); dog.run(); console.log(cat); cat.sayHello(); })(); /* OCP principle OPEN CLOSE principle of opening and closing Open for extension, closed for modification */ Copy code

3.4 super keyword

(function () { class Animal{ name: string; constructor(name: string){ this.name = name; } sayHello(){ console.log('Animals are calling~~') } } class Dog extends Animal{ age: number constructor(name: string, age: number){ //If the constructor is written in the subclass, the constructor of the parent class must be called in the subclass constructor super(name);//Call the constructor of the parent class this.age = age; } sayHello() { //In the method of the class, super means the parent class of the current class super.sayHello();//call the method of the parent class console.log('Wang Wang Wang~~') } } const dog = new Dog("Wang Cai", 3); dog.sayHello(); })() //Animals are calling~~ //Wow~~ Copy code

3.5 Abstract class

(function () { /* Classes beginning with abstract are abstract classes Abstract classes are not much different from other classes, but they cannot be used to create objects Abstract classes are classes that are specifically used to be inherited Abstract methods can be added to abstract classes */ abstract class Animal{ name: string; constructor(name: string){ this.name = name; } //Define an abstract method //The abstract method starts with abstract, there is no method body //Abstract methods can only be defined in abstract classes, and subclasses must override abstract methods abstract sayHello():void; //sayHello(){ //console.log('Animals are calling~~') //} } class Dog extends Animal{ sayHello() { console.log('Wang Wang Wang~~') } } class Cat extends Animal{ sayHello() { console.log(' ~~') } } const dog = new Dog("Wang Cai"); dog.sayHello(); const an = new Animal();//Cannot create an instance of an abstract class dog.sayHello(); })() Copy code

3.6 Interface

(function () { //Describe the type of an object type myType = { name: string, age: number }; /* Interface is used to define a class structure, which is used to define which attributes and methods should be included in a class At the same time, the interface can also be used as a type declaration */ interface myInterface{ name: string; age: number; } interface myInterface{ gender: string; } //Interface definitions will be merged const obj: myInterface = { name:'sss', age: 111, gender:'male' }; /* The interface can limit the structure of the class when defining the class None of the attributes in the interface can have actual values The interface only defines the structure of the object without considering the actual value All methods in the interface are abstract classes */ interface myInter{ name: string; sayHello(): void; } /* When defining a class, you can make the class implement an interface The realization of the interface is to make the class meet the requirements of the interface */ class MyClass implements myInter{ name: string; constructor(name: string){ this.name = name; } sayHello(){ console.log("Hello everyone~~~"); } } })(); Copy code

3.7 The difference between interface and type alias

3.7.1 Objects/Functions

Both interfaces and type aliases can be used to describe the shape or function signature of an object


interface Point { x: number; y: number; } interface SetPoint { (x: number, y: number): void; } Copy code

Type alias

type Point = { x: number; y: number; }; type SetPoint = (x: number, y: number) => void; Copy code

3.7.2 Other types

Unlike interface types, type aliases can be used for some other types, such as primitive types, union types, and tuples

//primitive type Name = string; //object type PartialPointX = {x: number; }; type PartialPointY = {y: number; }; //union type PartialPoint = PartialPointX | PartialPointY; //tuple type Data = [number, string]; Copy code

3.7.3 Extend

Both interfaces and type aliases can be extended, but the syntax is different. In addition, interfaces and type aliases are not mutually exclusive. Interfaces can extend type aliases, but not the other way around.

Interface extends interface

interface PartialPointX {x: number;} interface Point extends PartialPointX { y: number; } Copy code

Type alias extends type alias

type PartialPointX = {x: number; }; type Point = PartialPointX & {y: number; }; Copy code

Interface extends type alias

type PartialPointX = {x: number; }; interface Point extends PartialPointX {y: number;} Copy code

Type alias extends interface

interface PartialPointX {x: number;} type Point = PartialPointX & {y: number; }; Copy code

3.7.4 Implements

Classes can implement interfaces or type aliases in the same way, but classes cannot implement union types defined using type aliases:

interface Point { x: number; y: number; } class SomePoint implements Point { x = 1; y = 2; } type Point2 = { x: number; y: number; }; class SomePoint2 implements Point2 { x = 1; y = 2; } type PartialPoint = {x: number;} | {y: number; }; //A class can only implement an object type or //intersection of object types with statically known members. class SomePartialPoint implements PartialPoint {//Error x = 1; y = 2; } Copy code

3.7.5 Declaration merging

interface myInterface{ name: string; age: number; } interface myInterface{ gender: string; } const obj: myInterface = { name:'sss', age: 111, gender:'male' }; Copy code

3.8 Encapsulation of attributes

(function(){ //Define a class that represents people class Person{ //TS can add attribute modifiers before attributes /* Public modified attributes can be accessed (modified) at any location. Default value private private properties, private properties can only be accessed (modified) within the class -By adding methods to the class, private properties can be accessed externally protected protected attributes, can only be accessed (modified) in the current class and subclasses of the current class */ public _name: string; private _age: number; constructor(name: string, age: number) { this._name = name; this._age = age; } /* getter method to read attributes setter method to set properties -They are called attribute accessors */ /*//Define method to get name attribute getName(){ return this._name; } //Define method to set the name attribute setName(value: string){ this._name = value; } // getAge(){ return this._age; } setAge(value: number){ //Determine whether the age is legal if(value >= 0){ this._age = value; } } */ //The way to set the getter method in TS get name(){ console.log('get name() executed!!'); return this._name; } set name(value:string){ this._name = value; } set age(value:number){ if(value >= 0){ this._age = value } } } const per = new Person('The Monkey King', 18); /* Now the properties are set in the object, and the properties can be modified arbitrarily Attributes can be modified arbitrarily, which will cause the data in the object to become very insecure */ //per._name ='Pig Bajie'; //per._age = -38; //per.setName('Pig Bajie'); //per.setAge(-33); //console.log(per); per.name ='Pig Bajie'; per.age = -13 console.log(per); class A{ protected num: number; constructor(num: number){ this.num = num; } } class B extends A{ test(){ console.log(this.num); } } const b = new B(125); //b.num = 33//The attribute "num" is protected and can only be accessed in class "A" and its subclasses //class C{ //name: string; //age: number; ////You can directly define attributes in the constructor //constructor(name: string, age:number){ //this.name = name; //this,age = age; //} //} class C{ //Syntactic sugar //You can define attributes directly in the constructor constructor(public name: string, public age:number){ } } const c = new C('stoney',18); console.log(c); })(); Copy code

4. generic

When defining functions or classes, you can use generics if you encounter unclear types

function fn<T>(a:T):T { return a; } Copy code

Can directly call generic functions

let result = fn(10);//Do not specify generics, TS can automatically infer the type let result2 = fn<string>('hello');//Specify generics manually Copy code

Generics can specify multiple at the same time

function fn2<T, K>(a:T, b:K):T { console.log(b); return a; } fn2<number, string>(123,'hello'); Copy code

T extends Inter means that the generic T must be an Inter implementation class (subclass)

interface Inter{ length: number; } function fn3<T extends Inter>(a:T): number { return a.length } fn3('124'); //fn3(1243);//A parameter of type "1243" cannot be assigned to a parameter of type "Inter" fn3({length: 10}); Copy code
class MyClass<T>{ name: T; constructor(name:T){ this.name = name; } } const mc = new MyClass<string>('Sun Wukong'); Copy code

5. tsconfig.json file

{ /* tsconfig.json is the configuration file of the ts compiler, the ts compiler can compile the code with its information "include" is used to indicate which ts files need to be compiled path; * Indicates any file, ** indicates any directory "exclude" is used to indicate the directory of files that do not need to be compiled Default value: {"node_modules", "bower_components", "jspm_packages"} */ "include": [ "./src/**/*" ], //"exclude": [ //"./src/hello/**/*" //] //compilerOptions compiler options "compilerOptions": { //target is used to specify the version that ts is compiled into ES //'es3','es5','es6','es2015','es2016','es2017','es2018','es2019','es2020','esnext'. "target": "ES2015", //module specifies the specification of the modularity to be used //'none','commonjs','amd','system','umd','es6','es2015','es2020','esnext' "module": "es2015", //lib is used to specify the library used by the project //'es5','es6','es2015','es7','es2016','es2017','es2018','es2019','es2020','esnext','dom', //'dom.iterable','webworker','webworker.importscripts','webworker.iterable','scripthost','es2015.core','es2015.collection', //'es2015.generator','es2015.iterable','es2015.promise','es2015.proxy','es2015.reflect','es2015.symbol','es2015.symbol.wellknown','es2016.array .include', //'es2017.object','es2017.sharedmemory','es2017.string','es2017.intl','es2017.typedarrays','es2018.asyncgenerator','es2018.asynciterable','es2018.intl', //'es2018.promise','es2018.regexp','es2019.array','es2019.object','es2019.string','es2019.symbol','es2020.bigint','es2020.promise', //'es2020.sharedmemory','es2020.string','es2020.symbol.wellknown','es2020.intl','esnext.array','esnext.symbol','esnext.asynciterable','esnext.intl ', //outDir is used to specify the directory where the compiled file is located "outDir": "./dist", //outFile merges the code into one file //"outFile": "./dist/app.js", //Whether to compile the js file, the default is false "allowJs": true, //Whether to check whether the js code conforms to the syntax specification, the default value is false "checkJs": true, //Whether to remove the comment "removeComments": true, //Do not generate compiled files "noEmit": false, //Do not generate compiled files when there are errors "noEmitOnError": true, //Master switch for all strict inspections "strict": true, //Used to set whether the compiled file uses strict mode, the default is false "alwaysStrict": true, //Implicit any type is not allowed "noImplicitAny": true, //Ambiguous type this is not allowed "noImplicitThis": true, //Strictly check for null values "strictNullChecks": true } } Copy code