Types of assertions

Const nums = [2,66,88] // const res = nums.find(I => I >0) // // const t = res * res // const n2 = n1 * n1 console.log(n2) const n2 = n1 * n1 console.log(n2)Copy the code

The syntax for an assertion is variable xx as type xx or < type xx> variable xx, which tells TS that my code must be of a certain type and that it is safe to use it. In React, the < type xx> variable xx mode conflicts with the JSX syntax, so it is generally recommended to use the AS syntax.

Interface Interfaces

The basic use

Functionprint (post:Objpost){// There must be title and content console.log(post.title) console.log(post.content)} Print ({name:'xiling'}) print({name:'xiling') Functionprint (post:Objpost){// In the object that is passed in, Log (post.title) console.log(post.content)} print({name:'xiling'}) // error print({title:'lisi',content:66})Copy the code

Optional and read-only properties

Interface Objpost {// Attribute name: type // Use comma and semicolon or leave it blank title: string content: number subtitle? : string // Optional member attribute readOnly summary: string // Read-only attribute, which cannot be modified once assigned} // Parameter uses interface, annotates the content passed in, and meets the definition of interface functionprint(POST: Objpost) {// In the object passed in, Must have title and content console.log(post.title) console.log(post.content)} let obj:Objpost = { Title :'lisi',content:66,summary:'xiling'} obj.Copy the code

Members of the dynamic

InterfaceCache {// [props:string]:string} const obj: Cache = {} // Dynamic add object member obj.title='javaScript' obj.content=' HTML 'console.log(obj)Copy the code

The use of the class

The basic use

Constructor (name:string,age:number){this.name=name SayHi(string):void{console.log(' Hello ${this.name},${MSG} ')}} SayHi(string):void{console.log(' Hello ${this.name},${MSG} ')}}Copy the code

Access modifier

Class Person{// Public private protected // public public property, accessible anywhere // protected property, // private private attributes can be accessed only by themselves and their inherited subclasses, Public name:string='lisi' private age:number protected gender: Boolean constructor(name:string,age:number){ this.name=name this.age=age this.gender=true } SayHi(msg:string):void{ console.log(`Hello ${this.name},${msg}`) console.log(this.gender) } } class Student extends Person{ sya(){ this.gender } } let stu =newStudent('lisi',66) Stu. name stu.age// Private property, external access error; stu.gender// Protected property, external access errorCopy the code

Class read-only property

Class Person{// Set the member to read-only, once assigned, Public readOnly name:string='lisi' constructor(name:string,age:number){this.name=name} SayHi(MSG :string):void{public readonly name:string='lisi' constructor(name:string,age:number){this.name=name} SayHi(MSG :string):void{ This. Name ='liuneng'}Copy the code

Classes and interfaces

// Both humans and animals have sports and eating behaviors // Both have such behaviors, but they are different; Class Person {eat(food: string) {console.log(' Using chopsticks: ${food} ')} run(distance: distance) Number) {console.log(' feet: ${distance} ')}} class Animal {eat(food: food) String) {console.log(' Bite: ${food} '))} run(distance: number) {console.log(' four feet ${distance} ')}}Copy the code

People and animals both exercise and eat, they all do it, but it’s really different. In this case, we can use interfaces to describe different behavior constraints.

// Interface eatAndrun {eat(food: string):void run(distance: distance) Class Person implements eatAndrun {eat(food: food); String) {console.log(' Using chopsticks: ${food} ')} // Error if constraint member is missing // run(distance: Number) {// console.log(' feet: ${distance} ') //}}Copy the code

But in actual development, interface constraints will be more detailed, just like motorcycles can run, but not human or animal, detailed constraints will be more flexible.

Interface eat {eat(food: string):void} interface run {run(distance: distance) Class Person implements eat,run {eat(food: food); String) {console.log(' using chopsticks: ${food} ')} run(distance: number) {console.log(' Feet: ${distance} ')}}Copy the code

Abstract classes and abstract methods

An abstract class

Similar to interfaces, but interfaces can only be formally constrained and not implemented, whereas abstract classes can be implemented concretely. The definition of an abstract class is simple; you simply add abstract to the class declaration.

Abstract class Animal {eat(food:string):void{console.log(' Eat: ${food} ')}}Copy the code

Once a class is abstract, it cannot be instantiated and can only be used by subclass inheritance.

Class Dog extends Animal{} class Dog extends Animal{}Copy the code
Abstract methods
Abstract class Animal {eat(food:string):void{console.log(' bite to eat: ${food} ')} // Define abstract method run, Abstract run(distance:number):void} class Dog extends Animal{// The abstract method must implement run(distance:number) in the subclass. number):void { console.log(distance) }}Copy the code

The generic

A characteristic that is specified when defining a function, interface, or class without specifying a specific type until it is used.

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

Type declaration

When we do project development, we will definitely use some third party modules, but these third party modules are not necessarily TS, so we cannot use a strongly typed and friendly development experience.

For example, NPM install Lodash is used to install lodash and import it using the import syntax.

// The declaration file for module "lodash" could not be found. Import {camelCase} from'lodash' // camelCase convert string to hump const res =camelCase('hello xiling') // No type prompt console.log(res)Copy the code

The error message ‘cannot find declaration file for module’ lodash ‘was introduced. ‘

NPM install @types/lodash -d to fix this problem. The @types/lodash -d module is a declaration file.

Some modules own the declaration file directly, so there is no need to install additional extension libraries.

However, there are some relatively old libraries that have no declaration files of their own, and no corresponding file library that we have to deal with in our own code.

NPM uninstall@types /lodash uninstalls the type declaration file. In this case, the module “lodash” declaration file cannot be found.

CamelCase also has no type hint: there is really no type declaration file, so we tried to resolve camelCase’s type hint by using the DECLARE keyword:

// The declaration file for module "lodash" could not be found. Import {camelCase} from'lodash' declare functioncamelCase(input:string):string // camelCase Converts string to hump format const res =camelCase('hello xiling') // No type prompt console.log(res)Copy the code