TS and JS
- TypeScript’s strongest feature compared to JavaScript is strong typing, which supports both static and dynamic typing. Unlike JavaScript, strong typing allows you to discover and correct errors at compile time, reducing the cost of trial and error, and making your code more standardized.
TS example
- Let’s start with the current state of JS:
- JS in the variable itself is no type, variable can accept any different types of value, at the same time can access any attribute, attribute does not exist nothing more than return undefined
- Typeof variables is used to determine the typeof the current value
// JavaScript
var a = 123
typeof a // "number"
a = 'sdf'
typeof a // "string"
a = { name: 'Tom' }
a = function () {
return true
}
a.xxx // undefined
Copy the code
- What TS does is put type constraints on variables
- Limits that a variable assignment must provide a type-matching value
- Restrict variables to access only properties and methods that exist in the type to which they are bound
- As a simple example, here is a piece of javascript code that works
let a = 100 if (a.length ! == undefined) { console.log(a.length) } else { console.log('no length') }Copy the code
- Rewrite the above code directly with TS, setting the type of variable A to number. The syntax for setting the Type of a variable in TS is the [: Type] Type annotation
let a: number = 100 if (a.length ! == undefined) { // error TS2339: Property 'length' does not exist on type 'number'. console.log(a.length) } else { console.log('no length') }Copy the code
Create an array
- The way TS creates an array
let array1:Array<number>;
let array2:number[];
Copy the code
- JS to create an array
let array1 = new Array()
let array1 = []
Copy the code
- The array created by TS is only allowed to hold the same type of data.
- example
Let character: string [] = [" Yang guo, "" little dragon female", "Guo Xiang", "guo jing", "huang2 rong2", "li mo sorrow", 1); console.log(character); // Type 'number' is not assignable to type 'string'.Copy the code
- TS creates an array of object types
interface IArrStudent{
name:string,
age:number
}
const arrType5:Array<IArrStudent>=[{ name:"Mr.A",age:18},{ name:"Mr.B",age:20}]
const arrType6:IArrStudent[]= [{ name:"Mr.A",age:18},{ name:"Mr.B",age:20}]
Copy the code
- TS store if need an array of two kinds of data type, you need to use the joint type (string | number) [] the demo:
var foo: (string|number)[] = [ 1, "message" ];
Copy the code
! And?
Let y:number y = null; let y:number y = null; y = undefined!Copy the code
interface IDemo { x? : number } let y:number const demo = (parma: IDemo) = > {y = parma. X | | 1 / / if it is undefined, return y = 1, if not for undefined, it returns parma. The value of x return y}Copy the code
The little knowledge
- Typescript’s author is the father of C#, which has a very similar syntax to Java. So TS is easier for people who write Java to accept
Extends, implements
- Class implementation interface (support for multiple interface implementations)
// Animal interface Animal {type: string; sound: string; voice():void; } // Dog implements Animal {type:string; sound: string; Voice ():void {console.log(' ${this.sound}, I'm ${this.type} ')} constructor(sound: string,type: constructor) String) {this.sound = sound this.type = type}} // Cat implements Animal {type: string; sound: string; Voice (): void {console.log(' ${this.sound}, I'm ${this.type} ')} constructor(sound:string, type: constructor) string) { this.sound = sound; this.type = type; }} new Cat(" Cat ~"," Cat ").voice(); New Dog(" woof ~"," mammal ").voice();Copy the code
Results:
Meow, meow, I'm a mammal woof, I'm a mammalCopy the code
2. Interface inheritance Interface (support multiple inheritance)
// Creature {name: string; } // interface Animal extends Creature {// Action action(): void; } class Dog implements Animal { name: string; Action (): void {console.log(' I am ${this.name} ')} constructor (constructor) string) { this.name = name; }} new Dog(" Dog ").action() // I am a DogCopy the code
TIPS
- A class must implement all properties of its interface, including properties it inherits from its parent class
- Multiple Interface inheritance: An interface can inherit multiple interfaces
// Creature {name: string; } // Animal interface Animal {// own property action action(): void; } interface Dog extends Creature, Animal{color: string; } class Golden implements Dog { name: string; color: string; Action ():void {console.log(' I am ${this.name}, my color is ${this.color} ')} constructor(name: string, color:string) { this.name = name; this.color = color; }} I am a Golden retriever, my color is GoldenCopy the code
Golden implements the Dog interface, which inherits the Creature and Animal interfaces and owns their properties, so Golden implements them all.
- Class inheritance Class (single inheritance)
Class Person {name: string; constructor(name: string) { this.name = name; } run(): string {return '${this.name}'; }} let p = new Person(' Person '); console.log(p.run()); Person class extends Person {constructor(name: string) {super(name); }} let w = new Web(' li si '); console.log(w.run());Copy the code
Three characteristics of object oriented
- inheritance
Subclasses can inherit protected methods and properties from their parent class. Private means private properties cannot be obtained
- encapsulation
Meaning of encapsulation
- The point of encapsulation is to protect or prevent code (data) from being inadvertently corrupted.
- Protect member attributes from direct access and modification by programs outside the class;
- Hiding method details
- polymorphism
Conditions for polymorphism
- The existence of inheritance (inheritance is the basis of polymorphism, without inheritance there can be no polymorphism).
- Subclasses override methods of their parent classes (polymorphic calls down methods overridden by subclasses).
- Superclass reference variables point to subclass objects (subclass-to-superclass conversions).
/** * Animal is an abstract class that contains an abstract method */ abstract class Animal{public name:string; constructor(name:string){ this.name=name; } // an abstract method, which does not contain a concrete implementation, requires that subclasses implement this method. // Non-abstract methods, no need to subclass run(){console.log(' non-abstract methods, do not subclass, override '); }} class Dog extends Animal{eat(){return this.name+" meat "; }} class Cat extends Animal{eat(){return this.name+" eat fish "; } } var dog =new Dog("tom"); var cat=new Cat("kitty"); console.log(dog.eat()); console.log(cat.eat()); // Polymorphisms are different forms of a thing. // if f is Dog, then f at() calls the eat method of the Dog class. If it is Cat, then f.at () calls the eat method of Cat, which is polymorphic!! var f:Animal; // declare the variable as Animal //f=new Dog("sunny"); f=new Cat("sunny"); console.log(f.eat());Copy the code
An abstract class
- Abstract classes do not have to have abstract methods
- An abstract method must be an abstract class
- The parent class has abstract methods, and the subclass must implement abstract methods
- Abstract classes can only be used as base classes and cannot be instantiated (can’t new)
- If a subclass inherits an abstract class and overwrites all of its abstract methods, the class is an “entity class” that can be instantiated
- If a subclass inherits an abstract class and does not override all abstract methods, meaning that there are still abstract methods in this class, then this class must be declared abstract!
Difference between Type and interface
The official documentation
- An interface can be named in an extends or implements clause, but a type alias for an object type literal cannot.
- An interface can have multiple merged declarations, but a type alias for an object type literal cannot.
similar
- Type is used to define the type alias for the data. Interface is used to define the type alias of the data.
interface User {
name: string
age: number
}
interface SetUser {
(name: string, age: number): void;
}
Copy the code
type User = {
name: string
age: number
};
type SetUser = (name: string, age: number)=> void;
Copy the code
- Both allow for extends
interface Name {
name: string;
}
interface User extends Name {
age: number;
}
Copy the code
type Name = {
name: string;
}
type User = Name & { age: number };
Copy the code
type Name = {
name: string;
}
interface User extends Name {
age: number;
}
Copy the code
interface Name {
name: string;
}
type User = Name & {
age: number;
}
Copy the code
The difference between
- Type can declare basic type aliases, union types, tuples, and so on
- Interface can only define object types.
// Alias type Name = string // interface Dog {wong(); } interface Cat { miao(); =} type of Pet Dog | Cat / / specific define the type of array position of each type PetList = [Dog, Pet]Copy the code
- The type statement can also be assigned to the typeof the instance obtained using typeof
// when you want to get the typeof a variable, use typeof let div = document.createelement ('div'); type B = typeof divCopy the code
- Interface works and type doesn’t
Interface User {name: string age: number} interface User {sex: string} string age: number sex: string } */Copy the code
conclusion
- In general, if you don’t know when to use interface/type, if you can use interface, use interface, and if you can’t use type, okay
- According to the official documentation, interface is still recommended if you are building a public third-party library type.
- Interfaces are more inheritance oriented; Type, on the other hand, is more combinatorial.