Function type
- Add type to a function
- Type checks function parameters
- Type checks the return value of a function, as well as the function itself
1.1 Declaration of functions
function
Keyword to declare
// Restrict function arguments and return value types
function sum(a: string, b: string) :string { // After the parentheses is the return value
return a+b;
}
sum('a'.'b')
Copy the code
- Expression mode declaration
type Sum = (a:string,b:string) = > string;
let sum: Sum = (a:string,b:string) = > {
return a + b;
}
Copy the code
1.2 Optional Parameters
Use? The parameter of the flag indicates an optional parameter, that is, the parameter can be passed or not
letsum = (a:string,b? :string):string= > {
if(b){
return a + b;
}
return a;
}
sum('a') // Optional arguments must be at the end of other arguments
Copy the code
1.3 Default Parameters
Default and optional parameters cannot be applied to the same variable
let sum = (a: string, b: string = 'b') :string= > {
return a + b;
};
sum('a'); // The default argument must be at the end of the other arguments
Copy the code
1.4 Remaining Parameters
constsum = (... args: string[]):string= > {
return args.reduce((memo, current) = > memo += current, ' ')
}
sum('a'.'b'.'c'.'d')
Copy the code
1.5 Function Overloading
A function that performs different functions depending on how arguments are passed. The purpose of TS is to return different types according to different arguments
function toArray(value: number) :number[] / / overloadingfunction toArray(value: string) :string[] / / overloadingfunction toArray(value: number | string) {// True definitionif (typeof value == 'string') {
return value.split(' ');
} else {
return value.toString().split(' ').map(item= > Number(item));
}
}
toArray(123); // Returns different results depending on the type of data passed in
toArray('123');
Copy the code
Class two.
2.1 TS
Defined in the class
Instance attributes need to be declared before they are used, and arguments in constructors can take optional and residual arguments
class Pointer{ x! :number;// Attributes on instances must be declared firsty! :number;constructor(x:number,y? :number,... args:number[]){
this.x = x;
this.y = y asnumber; }}let p = new Pointer(100.200);
Copy the code
2.2 Modifiers in a class
public
Modifiers: Properties that anyone can access
class Animal { public name! : string;// Do not write public the default is also publicpublic age! : number;constructor(name: string, age: number) {
this.name = name;
this.age = age; }}class Cat extends Animal {
constructor(name: string, age: number) {
super(name, age);
console.log(this.name,this.age); // Subclass access}}let p = new Cat('Tom'.18);
console.log(p.name,p.age); // External access
Copy the code
protected
Modifiers: Attributes that are accessible only to you and your subclasses
class Animal {
constructor(protected name: string, protected age: number) { // We can simplify the superclass code by using parameter attributes
this.name = name;
this.age = age; }}class Cat extends Animal {
constructor(name: string, age: number) {
super(name, age);
console.log(this.name, this.age) // Subclasses are accessible}}let p = new Cat('Tom'.18);
console.log(p.name,p.age);// The external world is inaccessible
Copy the code
private
Modifiers: accessible only to yourself, inaccessible to others
class Animal {
constructor(private name: string, private age: number) {
this.name = name;
this.age = age; }}class Cat extends Animal {
constructor(name: string, age: number) {
super(name, age);
console.log(this.name, this.age); // Subclasses cannot be accessed}}let p = new Cat('Tom'.18);
console.log(p.name,p.age);// The external world is inaccessible
Copy the code
readonly
Modifiers: Marked as read-only properties that cannot be modified after initialization, except for objects
class Animal {
constructor(public readonly name: string, public age: number) {
this.name = name;
this.age = age;
}
changeName(name:string){
this.name = name; // Raise an exception. Read only attributes can only be assigned in constructor}}class Cat extends Animal {
constructor(name: string, age: number) {
super(name, age); }}let p = new Cat('Tom'.18);
p.changeName('Jerry');
Copy the code
Note: The constructor function can also add modifiers, though we rarely do so. By default, the constructor function is public, protected means that new cannot be called outside the constructor function, and private means that super cannot be used in subclasses
2.3 Static Properties and methods
Static properties and methods can be inherited by subclasses
class Animal {
static type = 'Mammals'; // Static es7 syntax
static getName() { // Static method
return 'Animal';
}
private _name: string = 'Tom';
get name() { // Attribute accessors
return this._name;
}
set name(name: string) {
this._name = name; }}let animal = new Animal();
console.log(animal.name);
Copy the code
2.4 Super properties
super
The default points to its own in constructors and static methodsThe parent class
- In the prototype approach
super
Point to theThe stereotype of the parent class
class Animal {
say(message:string){
console.log(message);
}
static getType(){
return 'animals'}}class Cat extends Animal {
say(){ // In the stereotype method, super refers to the stereotype of the parent class
super.say('Meow, meow, meow.');
}
static getType(){ // Static method super refers to the parent class
return super.getType()
}
}
let cat = new Cat();
console.log(Cat.getType())
Copy the code
Stereotype properties can be implemented in the form of property accessors
Class of decorators
Decorator is an experimental syntax, subject to change. It is used to extend properties and methods in a class. It cannot be used for decorators because functions have variable promotion issues.
3.1 decoration class
function addSay(target:any){
target.prototype.say = function(){console.log('say')}
}
@addSay
class Person { say! :Function
}
let person = new Person
person.say();
Copy the code
3.2 Decorates attributes in classes
Decorative attributes can be overwritten in the case of instance attributes and target to the prototype of the class, or static attributes and target to the class itself
function toUpperCase(target:any,key:string){ // target => class prototype, key is the modified property
let value = target[key];
Object.defineProperty(target,key,{
get(){
return value.toUpperCase();
},
set(newValue){
value = newValue
}
})
}
function double(target: any, key: string) {/ / target = > class
let value = target[key];
Object.defineProperty(target, key, {
get() {
return value * 2;
},
set(newValue) {value = newValue}
})
}
class Person {
@toUpperCase
name: string = 'Lucky7'
@double
static age: number = 10;
getName() {
return this.name; }}let person = new Person();
console.log(person.getName(),Person.age)
Copy the code
3.3 Decorates methods in a class
function noEnum(target:any,key:string,descriptor:PropertyDescriptor){
console.log(descriptor)
descriptor.enumerable = false;
}
class Person {
@toUpperCase
name: string = 'Lucky7'
@double
static age: number = 10;
@noEnum
getName() {
return this.name; }}let person = new Person();
console.log(person); // getName is not enumerable
Copy the code
3.4 Modifying Parameters
function addPrefix(target:any,key:string,paramIndex:number){
console.log(target,key,paramIndex); // Person.prototype getName 0
}
class Person {
@toUpperCase
name: string = 'Lucky7'
@double
static age: number = 10; prefix! :string @noEnumgetName(@addPrefix prefix:string) {
return this.name; }}Copy the code
4. Abstract classes
Abstract classes cannot be instantiated, only inherited, and abstract methods cannot be implemented in an abstract class, only in a concrete subclass of the abstract class, and must be implemented.
abstract class Animal{ name! :string; abstract speak():void
}
class Cat extends Animal {
speak(){
console.log('Meow the cat'); }}class Dog extends Animal{
speak():string{
console.log('Bark!');
return 'wangwang'}}Copy the code