What is the point of this section of code in Typescript?

I am reading a manual for Typescript, and I noticed a section of code that (for me) is pointless. Can anyone explain what the purpose of this is?

Taken from docs :

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

var greeter1: Greeter;
greeter1 = new Greeter();
alert(greeter1.greet());

var greeterMaker: typeof Greeter = Greeter; // This line
greeterMaker.standardGreeting = "Hey there!"; // This line
var greeter2:Greeter = new greeterMaker(); // And this line
alert(greeter2.greet());

So, what the docs say is that var greeterMaker: typeof Greeter = Greeter"the class itself will hold." I'm not quite sure what this means:

Then he does this:

greeterMaker.standardGreeting = "Hey there!";

// Which does the exact same thing as this:
Greeter.standardGreeting = "Hey there!";

What am I missing here?

+4
source share
3 answers

This works in the TS input system to get a reference to the class without declaring it greeterMakeras containing the class directly (I think it foo: class’s probably not allowed).

, Greeter, . , .

+1

, , Greeting typeof Greeting.

, , TypeScript , (1) (2) , , .

, :

class Greeter {
    static standardGreeting = "Hello, there";
    greeting: string;
    greet() {
        // ... code ...
    }
}

, , - , , longhand, :

interface Greeter {
  greet(): void;
}

var Greeter: {
  new(): Greeter;
  prototype: Greeter;
  standardGreeting: string;
};

Greeter = function () {};
Greeter.prototype.greet = function () {
  // ...code...
};

, Greeter, Greeter, Greeter, -. ( , , .)

Greeter - Greeter - , Greeter? - typeof. typeof Greeter " Getter", , Greeter, .

, . , , :

// This creates an alias called `greeterMaker` to the
// Greeter constructor function
// (functions are objects, and objects are always handled
// by-reference in JavaScript)
var greeterMaker: typeof Greeter = Greeter;

// This modifies the `standardGreeting` property of the
// function through the alias
greeterMaker.standardGreeting = "Hey there!";

// This invokes the constructor function through the alias,
// constructing a new instance of a Greeter
var greeter2:Greeter = new greeterMaker(); // And this line
+2

If you run the code, you will see that “Hello, there” should be displayed in the warning window. Following "Hello!".

A static variable cannot be changed in the Greeter class without creating a new one as Typeof.

if you try to add the line greeter.standardGreeting = "Hey there!";

It will be a mistake.

0
source

Source: https://habr.com/ru/post/1624009/


All Articles