1
1

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 で Object の keys からユニオン型を作りたい

1
Last updated at Posted at 2020-04-16

keyof typeof で取得する。忘れそうなのでメモ。

const Aspects = {
  "3x2": 3 / 2,
  "4x3": 4 / 3,
  "16x9": 16 / 9,
}
type Aspect = keyof typeof Aspects
// type Aspect = "3x2" | "4x3" | "16x9"
// と同じ

type AspectType = typeof Aspects

type AspectType = {
    "3x2": number;
    "4x3": number;
    "16x9": number;
}

と同じ型定義を作る。で、keyof で key から Union 型を作る

type Aspect = keyof AspectType

一行で定義すると、冒頭の書き方になる。

type Aspect = keyof typeof Aspects
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?