这个奇怪的JavaScript代码如何工作?神秘结肠 [英] How does this strange JavaScript code work? Mystery colon

查看:49
本文介绍了这个奇怪的JavaScript代码如何工作?神秘结肠的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在关注Angular 2官方教程,然后我看到了这段代码:

I'm following the official Angular 2 tutorial and then I saw this piece of code:

const HEROES: Hero[] = ...

const HEROES: Hero[] = ...

我不明白在HEROES之后冒号如何,我无法在JavaScript和TypeScript中找到有关此冒号用法的任何文档.我以为冒号仅用于对象键:值"和三元运算符.

I don't understand how the colon can be after HEROES, I can't find any documentation on this colon usage in JavaScript and TypeScript. I thought the colon were only used in object "key: value" and ternary operators.

export class Hero {
  id: number;
  name: string;
}

const HEROES: Hero[] = [
  { id: 11, name: 'Mr. Nice' },
  { id: 12, name: 'Narco' },
  { id: 13, name: 'Bombasto' },
  { id: 14, name: 'Celeritas' },
  { id: 15, name: 'Magneta' },
  { id: 16, name: 'RubberMan' },
  { id: 17, name: 'Dynama' },
  { id: 18, name: 'Dr IQ' },
  { id: 19, name: 'Magma' },
  { id: 20, name: 'Tornado' }
];

您能帮我理解这种冒号语法吗?

Can you help me understand this colon syntax?

答案中的其他问题并未解释打字稿,这是一种特殊的语法.

The other questions answer does not explain about typescript and that it is a special syntax.

推荐答案

这是TypeScript代码,这是您声明(注释)

This is TypeScript code, and this is how you declare (annotate) the type of a variable in TypeScript. The declaration means that the type of HEROES should be Hero[], an array of Hero objects.

var HEROES: Hero[];

TypeScript编译器将使用此信息来防止对该变量进行错误分配-例如,您不能将number分配给HEROES (不仅因为后者在您的代码中是常量,而且因为这将是类型错误).

The TypeScript compiler will use this information to prevent incorrect assignments to this variable -- for example, you cannot assign a number to HEROES (not just because the latter is a constant in your code, but because it would be a type-error).

类型声明可以在强类型编程语言中找到;例如,C#中的等效项将是:

Type declarations can be found in strong-typed programming languages; for example, an equivalent in C# would be:

Hero[] HEROES;

这篇关于这个奇怪的JavaScript代码如何工作?神秘结肠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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