2017-10-11 395 views
0

は、このようなパターンで「変数が割り当てられる前に使用される」パターン(TS2454)は

class stuff { 
    public id: string; 
    public uid: number; 
    constructor(parameter: string){ 
     this.id = parameter; 
    } 
    public getUID(): number { 
     return Date.now(); 
    } 
} 

let ids: number[]; /* 1: Here variable is not assigned */ 
for (let i = 0; i < 100; i++){ 
    ids[i] = new stuff(i.toString()).getUID(); 
    /* 2: Here ids[i] is used before initialized */ 
} 

を次のコードパターンを考慮して有用ではない、typescriptですが"strict": trueでコンパイルしないであろう。

私はlet ids:number[] | undefinedを実行できますが、それはtypescriptを使用するという価値を失います。

私は同じ動作を達成できる他のパターンはありますか?

ありがとうございました。

+1

以下は機能しますか? 'ids:number [] = []; 'and:' ids.push(new stuff(i.toString())。getUID()); ' – HMR

+1

なぜあなたは' ids'を初期化していませんか?コンパイラは、実行時に爆発する未定義の値に索引付けしていることを正しく警告しています。 – jcalz

+0

@HMR動作します。ありがとう。 – kalpa

答えて

2
let ids: number[] = []; 
for (let i = 0; i < 100; i++){ 
    ids.push(new stuff(i.toString()).getUID()); 
} 
+0

私がこれに対して行う唯一のことは、make idsをconstにすることです。 – Garfty

関連する問題