Reputation: 945
I'm having trouble understanding line 18 of the following snippet of a TypeScript tutorial.
1 class Greeter {
2 static standardGreeting = "Hello, there";
3 greeting: string;
4 greet() {
5 if (this.greeting) {
6 return "Hello, " + this.greeting;
7 }
8 else {
9 return Greeter.standardGreeting;
10 }
11 }
12 }
13
14 let greeter1: Greeter;
15 greeter1 = new Greeter();
16 console.log(greeter1.greet());
17
18 let greeterMaker: typeof Greeter = Greeter;
19 greeterMaker.standardGreeting = "Hey there!";
20
21 let greeter2: Greeter = new greeterMaker();
22 console.log(greeter2.greet());
As I understand from the tutorial, the goal of the declaration of greatermaker
is getting the Greeter class type into a variable, rather than the instance type.
Firstly, what is the function of the assignment operator =
in this line?
Secondly, what do we mean exactly with the distinction between the class type and the instance type? I guess, in the first we are able to manipulate the static member variables as opposed to the second?
Edit.
Why don't we just use let greeterMaker: typeof Greeter
, that is without the assignment operator?
Upvotes: 6
Views: 20058
Reputation: 945
(Tentative) expansion of @JGoodgive's comment.
An important thing to note is the distinction bewteen:
Greeter
, as in let var : Greeter
;Greeter
, as in var = new Greeter; typeof var;
var = Greeter
.It is key to note that the class type variable var = Greeter
is in fact the class constructor function. Hence, it is, incidentally and in particluar, of type Greeter
; because that is the class of which it is a public member function.
On another note, typeof Greeter
should return Greeter
according to the tutorial. This is because by Greeter
in typeof Greeter
, we mean the constructor function of the class Greeter
. And since, the constructor function returns the class itself (as an instance), it [the constructor function Greeter
] is of class type Greeter
, indeed.
Upvotes: 0
Reputation: 68655
The goal is to have the reference copy of the Greeter
class (actually function) into the variable greeterMaker
. With these you have 2 variables greeterMaker
and Greeter
to refer to the same class. So you can create objects of that class via
new Greeter()
or
new greeterMaker()
These two statements will do the same thing, because greeterMaker
is just another variable which refers to the Greeter
.
Upvotes: 3