Question

What's the formal difference between the types of these two variables in TypeScript?

var randomStringId = () => Math.random().toString(36).substr(2, 9);
function randomStringId2() {
    return Math.random().toString(36).substr(2, 9);
}

randomStringId has type () => string. randomStringId2 has type (): string. Are they different? If yes, how? Or is it just my IDE showing differently two types that are fundamentally the same?

Was it helpful?

Solution

Your functions are the same. However, these two functions are not:

var getX = () => this.x

function getX() {
    return this.x
}

look at the generated js code:

var _this = this;
var getX = function () {
    return _this.x;
};

function getX() {
   return this.x;
}

The function defined with arrow notation () => captures the reference to this when it is defined.

OTHER TIPS

Absolutely no difference in the Types. Both are exactly the same. They take nothing and return a string.

Here is the proof :

interface Foo1{
    foo:()=>string;
}
interface Foo2{
    foo():string;
}
var foo1:Foo1;
var foo2:Foo2;
foo1 = foo2 = foo1; 

However there is a difference in the way they behave. To understand the need for a lambda function ()=> : http://youtube.com/watch?v=tvocUcbCupA&hd=1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top