Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

What's the meaning of "=>" in TypeScript? (Fat Arrow)

I just start to learn TypeScript, and I saw there is a lot of code using this sytax =>. I did some research by reading the Specification of TypeScript Version 1.6 and some googling. I still cannot understand the meaning of =>.
To me, it feels like a pointer in C++. But I can't confirm it. If anyone can explain the following examples, that will be great. Thank you!

Below are some examples that I found when I was reading the specification of Typescript :

Object Types

var MakePoint: () => {  
    x: number; y: number;  
};

Question: What is this code doing? Creating an object called MakePoint, where x and y fields are number type? Is this a constructor or a function for MakePoint?

Function Types

function vote(candidate: string, callback: (result: string) => any) {  
 // ...  
}

Question: What is the meaning of => any? Do you have to return a string type?

Can anyone explain to me the difference or the purpose of these examples in plain english? Thank you for your time!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Perhaps you are confusing type information with a function declaration. If you compile the following:

var MakePoint: () => {x: number; y: number;};

you will see that it produces:

var MakePoint;

In TypeScript, everything that comes after the : but before an = (assignment) is the type information. So your example is saying that the type of MakePoint is a function that takes 0 arguments and returns an object with two properties, x and y, both numbers. It is not assigning a function to that variable. In contrast, compiling:

var MakePoint = () => 1;

produces:

var MakePoint = function () { return 1; };

Note that in this case, the => fat arrow comes after the assignment operator.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...