“="是什么意思?在打字稿中?(胖箭) [英] What's the meaning of "=>" in TypeScript? (Fat Arrow)

查看:37
本文介绍了“="是什么意思?在打字稿中?(胖箭)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习 TypeScript,我看到有很多代码使用这种语法 =>.我通过阅读 TypeScript 1.6 版规范 和一些谷歌搜索.我仍然无法理解 => 的含义.
对我来说,感觉就像 C++ 中的指针.但我无法确认.如果有人可以解释以下示例,那就太好了.谢谢!

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 =>.
For 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!

以下是我在阅读 Typescript 规范时发现的示例:

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

对象类型

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

问题:这段代码在做什么?创建一个名为 MakePoint 的对象,其中 x 和 y 字段是 number 类型?这是 MakePoint 的构造函数还是函数?

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 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 me the difference or the purpose of these examples in plain english? Thank you for your time!

推荐答案

也许您将类型信息与函数声明混淆了.如果你 编译以下内容:

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

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

你会看到它产生:

var MakePoint;

在 TypeScript 中,在 : 之后但在 =(赋值)之前的所有内容都是类型信息.所以你的例子是说 MakePoint 的类型是一个函数,它接受 0 个参数并返回一个具有两个属性的对象,xy,都是数字.它不是将函数分配给该变量.相比之下,编译:

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;

产生:

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

请注意,在这种情况下,=> 粗箭头出现在赋值运算符之后.

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

这篇关于“="是什么意思?在打字稿中?(胖箭)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆