I'm following Typescript handbook to learn about class.
Here is one of the examples:
class Greeter {
greeting: string;
constructor(message: string) {
this.greeting = message;
}
greet() {
return "Hello, " + this.greeting;
}
}
var greeter: Greeter; // return type: Greeter
greeter = new Greeter("world"); // implement greeter variable
alert(greeter.greet());
In typescript:
var greeter; // return type: any
var greeter: Greeter; // return type: Greeter (implicit convertion `any` to `Greeter`)
So, my question is: If we know exactly about the return type, why can't we use Greeter
instead of var
keyword?
What I wanna archive:
Greeter greeter = new Greeter("world"); // same to: var greeter = new Greeter("world");
This is done to keep consistency with javascript. The type definition can be omitted and TypeScript will automatically infer the type of the variable.
var greeter : Greeter = new Greeter();
Is the same as
var greeter = new Greeter();
This is slightly beside the point but you can also declare a variable that can hold multiple types. For example
var a : Greeter | number
Will hold a Greeter or a number. Having the type definition after the variable name is more elegant in my opinion.
What you want to accomplish is just not possible because it is not TypeScript syntax.
If you want to specify the type of a variable it is done like this:
var greeter: Greeter = new Greeter("world");
There are a lot of similarities to both Java and C# but the type system in TypeScript is different especially in syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With