2016-03-21 13 views

答えて

5

なぜクラスメンバーはTypeScriptで 'const'キーワードを使用できないのですか?以下が有効であるよう

constは深い不変性を意味するものではありません。その意味で

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

読み取り専用は、クラスのメンバーのためのより良い理にかなっているし、それはサポートされています:https://basarat.gitbooks.io/typescript/content/docs/types/readonly.html

+0

どのバージョンをTSの 'readonly'がサポートされていますか?それは[遊び場では動作しないようです](http://www.typescriptlang.org/Playground#src=class%20Foo%20%7B%0A%20%20%20%20readonly%20bar%20%3D %201%3B%0A%7D)。 – Aaron

+0

私は多分このようなものを書こうと思っていたかもしれません - > const foo:any = {bar:456};このコメントを削除します –

+1

@Aaron: 'readonly'はTSC 2.0でサポートされます。 https://github.com/Microsoft/TypeScript/wiki/Roadmap – Marc

2

まあ私の友人、私が知っている小さなものと私がここで行ったテストから、以下のコードが動作します。 "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() { 
 
    } 
 

 
}

関連する問題