0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【TypeScript】配列同士を結合する型の実装(type-challenges 初級編 533・Concat)

Last updated at Posted at 2024-12-06

お題

配列同士を結合する型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[]>
    TUが読み取り専用の配列のみ受け取るように制限する。
  • [...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()

スプレッド構文

今回の問題

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?