【发布时间】:2016-07-08 15:51:31
【问题描述】:
为什么类成员在 TypeScript 中不能有 'const' 关键字?
我在TypeScript documentation website 找不到任何有用的信息。
【问题讨论】:
标签: typescript
为什么类成员在 TypeScript 中不能有 'const' 关键字?
我在TypeScript documentation website 找不到任何有用的信息。
【问题讨论】:
标签: typescript
好吧,我的朋友,根据我所知道的和我在这里所做的测试,下面的代码可以工作。 “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() {
}
}
【讨论】:
为什么类成员在 TypeScript 中不能有 'const' 关键字?
const 并不意味着深度不变性,因此以下是有效的:
const foo:any = {};
foo.bar = 123; // Okay
从这个意义上说,readonly 对班级成员更有意义,并且得到支持:https://basarat.gitbooks.io/typescript/content/docs/types/readonly.html
【讨论】:
readonly 支持什么版本的 TS?它doesn't seem to work in the Playground.
readonly 将在 TSC 2.0 中得到支持。 github.com/Microsoft/TypeScript/wiki/Roadmap