Tân
Tân

Reputation: 1

Shorthand to declare "return type" in 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");

Upvotes: 4

Views: 477

Answers (3)

toskv
toskv

Reputation: 31612

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.

Upvotes: 5

Pablo
Pablo

Reputation: 642

It's simpler than that. You can actually do

var greeter = new Greeter("world");

The compiler is smart enough to infer the type from there.

EDIT: I'm sorry. I had misunderstood the question as if you didn't know about this syntax. The one the other answers mentioned is mostly what you want. That is:

var greeter: Greeter = new Greeter("world");

You can't go the Java way here since we are talking about different languages. It shouldn't take too long for you to get used to it. This is a really minor thing.

Upvotes: 2

Brocco
Brocco

Reputation: 64983

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.

Upvotes: 2

Related Questions