お題
タプル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演算子とは...
参考記事
今回の問題