1
1

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 初級編 18・Length of Tuple)

Last updated at Posted at 2024-12-04

お題

タプルTを受け取り、そのタプルの長さを返す型Lengthを実装する。

やりたいこと

type member = ["Tom", "John", "Mike"];
const color = ["red", "blue", "green", "yellow", "purple"] as const;

type memberLength = Length<member>; // 3
type colorLength = Length<typeof color>; // 5

解答

type Length<T extends readonly any[]> = T["length"];

解説

処理の流れ

  • <T extends readonly any[]>
    Tが読み取り専用の配列のみを受け取るように制約。
  • T["length"]
    ["length"]を使用し、タプルの要素の数を取得。

配列型の要素の数を取得するには...

["length"]を使用する。

type member = ["Tom", "John", "Mike"];
type memberLength = member["length"]; // 3

constアサーションとは...

typeof演算子とは...

参考記事

今回の問題

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?