在TypeScript中的'const'关键字

24 浏览
0 Comments

在TypeScript中的'const'关键字

为什么在TypeScript中类成员不能有'const'关键字?

我在TypeScript文档网站上找不到任何有用的信息。

0
0 Comments

在上述代码中,'const'关键字用于声明名为'HEROES'的常量数组。然而,在一个类的内部使用'const'关键字来声明常量是不合法的。为了解决这个问题,我们需要将'const'声明放在类的外部。

下面是修改后的代码:

import { Component, OnInit } from '/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() {
  }
}

通过将'const HEROES'的声明移至类的外部,我们解决了在类内部使用'const'关键字的问题。现在,代码将正常工作并且常量数组'HEROES'可以在类中使用。

0
0 Comments

在TypeScript中,为什么类成员不能使用'const'关键字?

在TypeScript中,'const'关键字并不意味着深度不可变性,因此以下代码是有效的:

const foo:any = {};
foo.bar = 123;  // Okay

从这个意义上讲,对于类成员来说,使用'readonly'关键字更合适,并且该关键字也被支持。具体可参考:[https://basarat.gitbooks.io/typescript/content/docs/types/readonly.html](https://basarat.gitbooks.io/typescript/content/docs/types/readonly.html)

在哪个版本的TypeScript中支持'readonly'关键字?在[Playground](http://www.typescriptlang.org/Playground#src=class%20Foo%20%7B%0A%20%20%20%20readonly%20bar%20%3D%201%3B%0A%7D)中似乎不起作用。

我认为你可能想写类似于以下代码:const foo:any = { bar: 456 }; 我将删除这条评论。

'readonly'关键字将在TSC 2.0中得到支持。具体可参考:[https://github.com/Microsoft/TypeScript/wiki/Roadmap](https://github.com/Microsoft/TypeScript/wiki/Roadmap)

0