Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shorthand to declare "return type" in typescript

Tags:

typescript

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");
like image 973
Tân Avatar asked Jan 07 '23 18:01

Tân


2 Answers

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.

like image 165
toskv Avatar answered Jan 20 '23 15:01

toskv


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.

like image 21
Brocco Avatar answered Jan 20 '23 13:01

Brocco