19
5

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 1 year has passed since last update.

【Typescript】特定の数字しか入らない配列の型を作る

Last updated at Posted at 2022-02-27

何がしたい

  • [1, 8, 9] しか入らない配列の型を作りたい
  • 1, 8, 9 全てが入る場合もある
  • 1 だけ入る場合もある
  • 8, 9 の2つが入る場合もある
  • [9, 1, 8] のように順番が並び変わるケースもある
const NumArray = [1, 8, 9] // 全部入る場合
const NumArray = [1] // 1つだけ入る場合
const NumArray = [8, 9] // 2つだけ入る場合
const NumArray = [9, 1, 8] // 順番が並び変わるケースもある

結論

type SpecificNumber = (1 | 8 | 9)[];
const NumArray:SpecificNumber = [1] // 1つだけ入る場合
const NumArray:SpecificNumber = [8, 9] // 2つだけ入る場合
const NumArray:SpecificNumber = [9, 1, 8] // 順番が並び変わるケースもある

参考

ちゃんとサバイバルTypescriptに書いてあった、、、
しかも「よくある間違い」にもしっかり引っかかってしまった、、
配列要素にユニオン型を使う際の書き方

19
5
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
19
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?