LoginSignup
4
1

Recordとは?

簡単に言うとインデックス型([key: string])やMapと同じくkeyValueオブジェクトの型です。

しかし[key: string]やMapよりも直感的に型付けすることができます。

let a: Record<string, number>;

let b: { [K: string]: number };
let c: Map<string, number>;

具体的な型付け方法

Key側に設定できる型はstring, number, symbolとその3種類のリテラルになります。

またvalue側に設定できる型はなんでもできます。

let a: Record<string, number>; // OK
let b: Record<number, number>; // OK
let c: Record<symbol, number>; // OK;
let d: Record<"" | "" | "", number>; // OK

type Human = {
  name: string;
}
let e: Record<string, Human>; // OK
let e: Record<Human, number>; // NG

インデックス型([key: string])と違い

Keyに対してリテラルを設定できるようになっています。

// OK
let a: Record<"" | "" | "", number>; 

// NG An index signature parameter type cannot be a literal type or generic type. Consider using a mapped object type instead.
let b: { [key: "" | "" | ""]: number}; 
4
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
4
1