0
0

TypeScriptの型操作入門 keyof typeof の活用法

Posted at

typeof 型演算子とは

typeof は変数から型を抽出する型演算子です。

例として以下のようなオブジェクトがあったとします。

const person = {
  name: "John",
  age: 26,
};

上記オブジェクトに対して typeof を使った型は次のような型になります。

type Person = typeof person;
type Person = {
  name: string;
  age: number;
};

keyof 型演算子とは

keyof はオブジェクトの型からプロパティ名を型として返す型演算子です。

例として以下のようなオブジェクトの型があったとします。

type Person = {
  name: string;
  age: number;
};

上記オブジェクトの型に対して keyof を使った型は次のような型になります。

type PersonKey = keyof Person;
type PersonKey = "name" | "age";

keyof typeof を同時に使う

keyoftypeof を同時に使えば、オブジェクトのプロパティ名から型を抽出できます。

const Book = {
  title: "sample book",
  price: 1000,
  author: "Mike",
};

上記オブジェクトに対して keyof typeof を使った型は次のような型になります。

type BookKey = keyof typeof Book;
type BookKey = "title" | "price" | "author";

また、オブジェクトの末尾に as const を記述することで、オブジェクトの Value を型にすることができます。
(as const 記述することで、プロパティすべてを readonly で指定したものと同等の扱いになります。)

const Book = {
  title: "sample book",
  price: 1000,
  author: "Mike",
} as const;

上記オブジェクトに対して BookValue の型は次にようになります。

type BookKey = keyof typeof Book;
type BookValue = (typeof Book)[BookKey];
type BookValue = "sample book" | 1000 | "Mike";
0
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
0
0