2
2

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: FixedArray<T, L> ─ サイズ固定の配列型を作るユーティリティ型

Posted at

TypeScriptで配列の要素数を決め打ちした配列型を作るユーティリティ型です。

FixedArray<T, L>

type FixedArray<T, L extends number> =
    L extends 0 ? [] : [T, ...T[]] & { length: L }

Tに要素の型を、Lに配列のサイズを指定します。

使用例

let t0: FixedArray<number, 0>
t0 = []
t0 = [1] // Error

let t1: FixedArray<number, 1>
t1 = [] // Error
t1 = [1]
t1 = [1, 2] // Error

let t2: FixedArray<number, 2>
t2 = [1] // Error
t2 = [1, 2]
t2 = [1, 2, 3] // Error

let t3: FixedArray<number, 3>
t3 = [1, 2] // Error
t3 = [1, 2, 3]
t3 = [1, 2, 3, 4] // Error

制約

この型の制約として、ミューテーションメソッドで要素数が変わってしまうと実行時エラーになります:

const t1: FixedArray<string, 1> = ['foo']
t1.pop()
t1[0].toUpperCase()
// ERR: Cannot read property 'toUpperCase' of undefined 

試す

このユーティリティタイプを試したい方は、TypeScript Playgroundをご覧ください。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?