【问题标题】:'const' keyword in TypeScriptTypeScript 中的“const”关键字
【发布时间】:2016-07-08 15:51:31
【问题描述】:

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

我在TypeScript documentation website 找不到任何有用的信息。

【问题讨论】:

标签: typescript


【解决方案1】:

好吧,我的朋友,根据我所知道的和我在这里所做的测试,下面的代码可以工作。 “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() {
  }

}

【讨论】:

    【解决方案2】:

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

    const 并不意味着深度不变性,因此以下是有效的:

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

    从这个意义上说,readonly 对班级成员更有意义,并且得到支持:https://basarat.gitbooks.io/typescript/content/docs/types/readonly.html

    【讨论】:

    猜你喜欢
    • 2018-11-01
    • 1970-01-01
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    • 2010-11-27
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多