当前位置:网站首页>Typescript class and interface, class and generic, interface merging

Typescript class and interface, class and generic, interface merging

2022-06-11 07:59:00 YY little monster

Details visible
1. Classes and interfaces

1. class " Realization " Interface 
interface PersonInterface {
    
    name:string;
    say():void;
}
//  Just implement an interface ,  Then you must implement all the properties and methods in the interface 
class Person implements PersonInterface{
    
    name:string = 'lnj';
    say():void{
    
        console.log(` My name is :${
      this.name}`);
    }
}
let p = new Person();
p.say();
2. Interface " Inherit " class 
class Person {
    
    // protected name:string = 'lnj';
    name:string = 'lnj';
    age:number = 34;
    protected say():void{
    
        console.log(`name = ${
      this.name}, age = ${
      this.age}`);
    }
}
// let p = new Person();
// p.say();
 Be careful :  As long as an interface inherits a class ,  Then it will inherit all the properties and methods in this class 
         But it only inherits the declarations of properties and methods ,  Does not inherit property and method implementations 
 Be careful :  If the class inherited by the interface contains protected Properties and methods of ,  Then only subclasses of this class can implement this interface 
interface PersonInterface extends Person{
    
    gender:string;
}

class Student extends Person implements PersonInterface{
    
    gender:string = 'male';
    name:string = 'zs';
    age:number = 18;
    say():void{
    
        console.log(`name = ${
      this.name}, age = ${
      this.age}, gender = ${
      this.gender}`);
    }
}
let stu = new Student();
stu.say();

2. Classes and generics

//  Generic classes 
class Chache<T> {
    
    arr:T[] = [];
    add(value:T):T{
    
        this.arr.push(value);
        return value;
    }
    all():T[]{
    
        return this.arr;
    }
}
let chache = new Chache<number>();
chache.add(1);
chache.add(3);
chache.add(5);
console.log(chache.all());

3. Interface merging

 When we define multiple interfaces with the same name ,  The contents of multiple interfaces are automatically merged 
interface TestInterface {
    
    name:string;
}
interface TestInterface {
    
    age:number;
}
 become 
interface TestInterface {
    
    name:string;
    age:number;
}


class Person implements TestInterface{
    
    age:number = 19;
    name:string = 'lnj';
}

原网站

版权声明
本文为[YY little monster]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206110754014685.html