TypeScript におけるタプルの型

TypeScript では、要素数が限定された配列をタプルと呼ぶ。 タプル型には面白い特徴がある。 const foo = ["a", 1]; としたとき foo の型は [string, number] ではなく (string | number)[] になる。したがって、次のコードは failTuple の初期化時に型エラーになる。 const foo = ["a", 1]; // (string | number)[] const failTuple: [string, number] = foo; // 型エラー!! これを回避するための簡単な方法は、型を明示的に指定することである。具体的には次のようにする。 const bar: [string, number] = ["a", 1]; // [string, number] const successTuple: [string, number] = bar; as const をつけて変数を初期化することもできる。次の例では bar の型は readonly [string, number] となり、タプルの中身は変更できない。 const bar: [string, number] = ["a", 1]; // readonly [string, number] const successTuple: [string, number] = bar; // successTuple[0] = "b"; // エラー! [Read More]

JavaScript/TypeScript の Array.prototype.reduce() でハッシュを作る

JavaScript/TypeScript における Array.prototype.reduce() (以下、reduce() とする) は配列から単一の値を作るために使われるメソッドである。典型的には次のような使われ方をする。 const total = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].reduce((prev: number, curr: number) => { return prev + curr; }, 0); console.log(total); // 55 配列にある複数の要素を、単一の値に reduce (= まとめあげ) している、ということだ。 reduce で、配列を単一のハッシュに変換することもできる。次のような配列を考えよう。 [ { name: "ケンシロウ", style: "北斗神拳", strength: 10, }, { name: "ジャギ", style: "北斗神拳", strength: 5, }, { name: "レイ", style: "南斗聖拳", strength: 8, }, ]; これを次のように変換したいとする。 { "ケンシロウ": { "style": "北斗神拳", "strength": 10 }, "ジャギ": { "style": "北斗神拳", "strength": 5 }, "レイ": { "style": "南斗聖拳", "strength": 8 } } この変換は reduce を使うと簡単に実現できる。 [Read More]