Declaring a class type variable in Typescript
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
.
Mussé Redi
Updated on June 25, 2022Comments
-
Mussé Redi almost 2 years
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?