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 初級編 3057・push 解説

Last updated at Posted at 2024-12-12

お題

タプルに要素を追加する型PushArray.pushのジェネリックバージョン)を実装する。

やりたいこと

type Result = Push<[1, 2], '3'> // [1, 2, '3']

解答

type Push<T extends unknown[], U> = [...T, U];

解説

処理の流れ

  • <T extends unknown[], U>
    タプルに要素を追加するので、Tに制限をかける。
  • [...T, U]
    スプレッド構文で展開したTの要素とUを[]でラッピングし、新たなタプルを作成する。

配列型を扱う注意点

type T = number[]; // 配列型
type Result = [...T, boolean]; // エラー

スプレッド構文とは...

今回の問題

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?