お題
配列同士を結合する型Concat
を実装する(JavaScriptのArray.concat
関数を型システムに実装する)。
やりたいこと
const tuple = [1] as const
type Result1 = Concat<[1], [2, 3]> // => [1, 2, 3]
type Result2 = Concat<typeof tuple, typeof tuple> // => [1, 1]
type Result3 = Concat<[1, "a"], [true, 2]> // => [1, "a", true, 2]
解答
type Concat<T extends readonly any[], U extends readonly any[]> = [...T, ...U];
解説
処理の流れ
-
<T extends readonly any[], U extends readonly any[]>
T
とU
が読み取り専用の配列のみ受け取るように制限する。 -
[...T, ...U]
それぞれの要素をスプレッド構文によって展開し、配列を結合する。
そもそもArray.concat
関数とは...
Array.
インスタンスのメソッドで、2つ以上の配列を結合する際に使用する。既存の配列を変更せず、新しい配列を返す。
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
console.log(array3); // => ["a", "b", "c", "d", "e", "f"]
スプレッド構文とは...
- 配列に
...
を使用することで、要素を展開できる。 - 好きな位置に記述できるので、要素と要素の間に挿入することも可能。
const arr = [1, 2, 3];
const newArr1 = [...arr, 4]; // => [1, 2, 3, 4]
const newArr2 = [0, ...arr, 4]; // => [0, 1, 2, 3, 4]
typeof演算子とは...
参考記事
Array.prototype.concat()
スプレッド構文
今回の問題