Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Class and interface in TypeScript


May 31, 2021 Article blog


Table of contents


The article comes from the public number: The Clown's Cabin

preface

Just vue3.0 the major web sites and communities as well as the public number has been Vue Piece 3.0 version of One Piece screen, the appearance of different titles with the same content phenomenon, so we might as well review the ts prepare for the official use of vue3.0

TypeScript this thing is true, it is really easy to forget, a period of time without feeling particularly strange, but looking back, there is a familiar feeling, there is a saying that: ts more fragrant, it can indeed regulate our writing format, grammar checksum type check and so on. I've written a demo about react+ts before, but I've forgotten it over time, and now it's time to review the contents of ts as well as some higher-order syntax, and now we look back at the classes and interfaces that are common in ts

class

One thing we need to be clear about on the front page is the difference between classes in TypeScript and ES6 syntax classes in JavaScript, so don't get confused. T he type of declared property and the type of argument and the type of result returned are added in ts compared to js. This place is wrong to write at first glance, and if you don't declare ts, you'll get it wrong.

class Person{
    name:string;
    constructor(name:string){
        this.name = name;
    }
    getName():void{
        console.log(this.name);
    }
}
class Person{
    constructor(name){
        this.name = name;
    }
    getName(){
        console.log(this.name);
    }
}

ES5 edited results

var Person = /** @class */ (function () {
    function Person(name) {
        this.name = name;
    }
    Person.prototype.getName = function () {
        console.log(this.name);
    };
    return Person;
}());

The get and set of the class

ts when compiling get and set is compiled by default es3 compilation, vscode editor will report error error TS1056: Accessors are only available when targeting ECMAScript 5 and higher need to compile to version ES5 or above, solution: $ tsc xxx.ts -t es5

class User{
    myname:string;
    constructor(myname:string){
        this.myname = myname
    }
    get name(){
        return this.myname
    }
    set name(newName:string){
        this.myname = newName
    }
}

The result of the ES5 compilation

var User = /** @class */ (function () {
    function User(myname) {
        this.myname = myname;
    }
    Object.defineProperty(User.prototype, "name", {
        get: function () {
            return this.myname;
        },
        set: function (newName) {
            this.myname = newName;
        },
        enumerable: false,
        configurable: true
    });
    return User;
}());

Here are a few thought questions, the answer is at the end of the article :

var u = new User("a");
console.log(u);
console.log(u.myname);
u.myname = 'b';
console.log(u.myname);
console.log(u.hasOwnProperty("name"));
console.log(Object.getPrototypeOf(u));
console.log(Object.getPrototypeOf(u).hasOwnProperty("name"));

Abstract class

abstract keywords represent abstract classes, abstract classes can not be instantiated that is new, can only be inherited, abstract classes are generally used to encapsulate some common, provided to subclasses to use methods and properties

abstract class Animal{
    public readonly name:string;
    protected age:number = 38;
    private money:number = 10;
    constructor(name:string){
        this.name = name
    }
}
class Dog extends Animal{
    static className = 'Dog'
    static getClassName(){
        console.log(this.className)
    }
    getName(){
        console.log(this.name)
    }
    getAge(){
        console.log(this.age)
    }
}
let a = new Animal("ss");

Print here to see the results of inheritance:

console.log(a); //Dog { age: 38, money: 10, name: 'ss' }

Here, by the way, the access modifier public protected private

  • public can be accessed both inside and outside, including yourself, your own subclasses, and other classes
  • Protected itself and subclasses can be accessed but not elsewhere
  • private private (only you can access it yourself, and none of the other subclasses can access it)

interface

 Class and interface in TypeScript1

The interface represents the properties of the object

interface Rectangle {
    width: number;
    height: number
}


let r: Rectangle = {
    width: 100, height: 10
}


interface Speakable {
    speak(): void;
    name?: string
}


let speaker: Speakable = {
    //name:"bdt",
    speak() { }
}

Interfaces are used to describe abstract behavior

interface AnimalLink {
    eat(): void;
    move(): void
}

Interfaces can be inherited

interface PersonLike extends AnimalLink {
    speak(): void
}
class Person2 implements PersonLike {
    speak() { };
    eat() { };
    move() { }
}

The variable type is constrained by the interface

interface Person3 {
    readonly id: number;
    name: string;
    [PropName: string]: any
}
let p1: Person3 = {
    id: 1,
    name: "sss"
}

The function is constrained (canonically) by interface

interface DiscountInterface{
    (price:number):number
}
let discount:DiscountInterface = function (price: number): number {
    return price * .8
}

An array and objects are constrained by an index

interface UserInterface{
    [index:number]:string
}


let arr:UserInterface = ['aa','bb']


interface UserInterface2{
    [index:string]:string
}
let obj:UserInterface2  = {name:"sss"}

The constructor is constrained by an interface

class Animal3{
    constructor(public name:string){}
}
interface WithClassName{
    new (name:string):Animal3
}
function createClass(clazz:WithClassName,name:string){
    return new clazz(name)
}
let a3 = createClass(Animal3,"别抖腿");
console.log(a3)

The difference between class and interface

  • The class class declares and implements the method
  • The interface interface declares, but the method cannot be implemented

abstract class Animal{
    name:string="111";
    abstract speak():void;  //抽象类和方法不包含具体实现  必须在子类中实现
}
//接口里的方法都是抽象的
interface Flying{
    fly():void
}
interface Eating{
    eat():void
}
class Dog extends Animal{
    speak(){
        console.log("汪汪汪")   //重写:子类重写继承自父类中的方法
    }
}
class Cat extends Animal implements Flying,Eating{
    speak(){   //继承抽象类的方法必须实现
        console.log("喵喵喵")
    }
    fly(){
        console.log("我是一只飞货")
    }
    eat(){
        console.log("我是一只吃货")
    }
}

written at last

The answer in the text

User { myname: 'a' }
a
b 
false
User { name: [Getter/Setter] }
true

That's what W3Cschool编程狮 has to say about class and interface in TypeScript, and I hope it's helpful.