5
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 5 years have passed since last update.

TypeScriptで配列の要素をUnionで取得する

5
Last updated at Posted at 2019-07-29

結論


const array = ['山田', '田中', '鈴木'] as const;
type LastNames = typeof array[number]; // => '山田' | '田中' | '鈴木'

何がしたかったか

as constで定数化した配列の要素のうち、いずれかを受け取るよう関数を書きたかったのですが、地味に悩みました。
配列の0番目の要素|残りの要素みたいな形で再帰的にやるのか?とか、keyofでとってきた中から'0'だけ省いて?とか色々考えましたが、前者はかなり面倒、後者はarrayのプロパティがずらずら付いてきてしまうので断念。

そのときふと、keyofで取得した中にnumberがいたので、試してみたらあっけなく出来ました…。

追記

keyof any[]をすると、配列のメソッドのキー名等も取り出されてしまいますが、インデックスのみが欲しい場合、type PickIndex<T extends any[]> = Exclude<keyof T, keyof any[]>;で実現できます。


const array = ['山田', '田中', '鈴木'] as const;
type PickIndex<T extends ReadonlyArray<any>> = Exclude<keyof T, keyof any[]>;
type Indexes = PickIndex<typeof array>; // => '0' | '1' | '2'
5
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
5
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?