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?

lengthの調べ🎻 型の世界に響く優雅な旋律

Last updated at Posted at 2025-03-07

lengthとは?

まぁ!length についてのお話ですわね?
TypeScriptにおきましては、タプルや配列の長さを組み込みの length プロパティを用いて取得することができますのよ。

// タプルの長さを取得する型
type Length<T extends readonly any[]> = T['length'];

// 使用例
type SampleTuple = [string, number, boolean];
type SampleLength = Length<SampleTuple>; // 結果は3

補足(extendsについて)

extends とは、型に制約を設けるためのエレガントな仕組みですわ。

type IsString<T> = T extends string ? true : false;

type A = IsString<string>; // true
type B = IsString<number>; // false

また、Length 型は readonly any[] を制約として指定しておりますので、
タプルや配列以外の型を渡しますと、無粋にもエラーとなってしまいますの。


まとめ

  • length を使用することで、タプルや配列の長さを優雅に取得できますわ。
  • extends を用いることで、型に制約を設けたり、条件分岐を行うことができますのよ。

まぁ!これで length の理解もより深まりましたわね?ふふっ🎀

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?