TypeScript: Class

 20th August 2020 at 2:19pm

Instance side vs static side

class Greeter {
    static standardGreeting = "Hello, there";
    greeting: string;
    greet() {
        if (this.greeting) {
            return "Hello, " + this.greeting;
        }
        else {
            return Greeter.standardGreeting;
        }
    }
}

// greeter1 的类型是「Greeter 实例」
let greeter1: Greeter;
greeter1 = new Greeter();
console.log(greeter1.greet());

// greeterMaker 的类型是「Greeter」
let greeterMaker: typeof Greeter = Greeter;
greeterMaker.standardGreeting = "Hey there!";

let greeter2: Greeter = new greeterMaker();
console.log(greeter2.greet());