TypeScript 中的“const”关键字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36142879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
'const' keyword in TypeScript
提问by tautvisv
Why a class member cannot have the 'const' keyword in TypeScript?
为什么类成员在 TypeScript 中不能有“const”关键字?
I cannot find any usefull information about it at TypeScript documentation website.
我在TypeScript 文档网站上找不到任何有用的信息。
回答by basarat
Why a class member cannot have the 'const' keyword in TypeScript?
为什么类成员在 TypeScript 中不能有“const”关键字?
const
does not imply deep immutability so the following is valid:
const
并不意味着深度不变性,因此以下内容有效:
const foo:any = {};
foo.bar = 123; // Okay
In that sense readonlymakes better sense for class members and that is supported : https://basarat.gitbooks.io/typescript/content/docs/types/readonly.html
从这个意义上说,readonly对班级成员更有意义,并且得到支持:https: //basarat.gitbooks.io/typescript/content/docs/types/readonly.html
回答by Rafael Moura
Well my friend, from the little that I know and the test I did here, the code below will work. The "const..." needs to be outside of class, like below:
好吧,我的朋友,根据我所知道的一点点和我在这里所做的测试,下面的代码将起作用。“const...”需要在课堂之外,如下所示:
import { Component, OnInit } from '@angular/core';
const HEROES: any[] = [
{id: 1, name: "Rafael Moura"},
{id: 2, name: "Hulk"},
{id: 3, name: "Iron Man"},
{id: 4, name: "Spider-Man"},
{id: 5, name: "Super-Man"},
{id: 6, name: "Thor"},
{id: 7, name: "Wolverine"},
{id: 8, name: "Cyclop"},
{id: 9, name: "Magneto"},
{id: 10, name: "Arrow"},
{id: 11, name: "Geen"}
]
@Component({
selector: 'app-component-heroes',
templateUrl: './component-heroes.component.html',
styleUrls: ['./component-heroes.component.css']
})
export class ComponentHeroesComponent implements OnInit {
title = "Tour of Heros";
heroes = HEROES;
constructor() {
}
ngOnInit() {
}
}