0

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?

2
  • 1
    To understand the lambda syntax : youtube.com/watch?v=tvocUcbCupA&hd=1 Commented May 7, 2014 at 10:33
  • You have to be careful as the first one is a variable holding a function, and the second one is a defined function itself. randomStringId2 can be used BEFORE its declaration, while randomStringId cannot. This is pure JavaScript differences and since TypeScript is a superset of JavaScript, it inherits this difference. Commented May 8, 2014 at 5:21

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.