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

More than 3 years have passed since last update.

[TypeScript] 自然数型を定義する

Posted at

TypeScriptの練習のために [0, 1, 2, 3, 4, 5 ・・・] となる自然数型を作ってみました。

実装

v4.0.2
type NaturalNumber<Num extends number> = Rec<Num, []>;

type Rec<Num, C extends unknown[]> = {
  0: C,
  1: Rec<Num, Append<C, C['length']>>
}[C['length'] extends Num ? 0 : 1];

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

type Test = NaturalNumber<5>; // => [0, 1, 2, 3, 4]

動作確認

Screen Shot 2020-09-09 at 22.45.29.png

45までが限界でした。

参考

TypeScriptで最低n個の要素を持った配列の型を宣言する方法 - Qiita
TypeScript: Append<[1,2], 3> ─ タプル型の最後に要素を追加するユーティリティ型 - Qiita

1
0
2

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