メインコンテンツまでスキップ

インデックスアクセス型 (indexed access types)

TypeScriptのインデックスアクセス型(indexed access type)は、プロパティの型や配列要素の型を参照する方法を提供します。

ts
type A = { foo: number };
type Foo = A["foo"];
type Foo = number
ts
type A = { foo: number };
type Foo = A["foo"];
type Foo = number

インデックスアクセス型の構文

インデックスアクセス型は、型に対してブラケット表記法を使います。

ts
オブジェクト型["プロパティ名"];
配列型[number];
ts
オブジェクト型["プロパティ名"];
配列型[number];

オブジェクトの型とインデックスアクセス型

インデックスアクセス型にはユニオン型も使えます。

ts
type Person = { name: string; age: number };
type T = Person["name" | "age"];
type T = string | number
ts
type Person = { name: string; age: number };
type T = Person["name" | "age"];
type T = string | number

keyof型演算子と組み合わせると、オブジェクトの全プロパティの型がユニオン型で得られます。

ts
type Foo = { a: number; b: string; c: boolean };
type T = Foo[keyof Foo];
type T = string | number | boolean
ts
type Foo = { a: number; b: string; c: boolean };
type T = Foo[keyof Foo];
type T = string | number | boolean

もしもオブジェクトの型に存在しないプロパティ名を指定すると、コンパイラが警告を出します。

ts
type Account = { name: string };
type T = Account["password"];
Property 'password' does not exist on type 'Account'.2339Property 'password' does not exist on type 'Account'.
ts
type Account = { name: string };
type T = Account["password"];
Property 'password' does not exist on type 'Account'.2339Property 'password' does not exist on type 'Account'.

配列型とインデックスアクセス型

配列型の要素の型を参照するのにもインデックスアクセス型が使えます。要素の型を参照するには、配列型に[number]をつけます。

ts
type StringArray = string[];
type T = StringArray[number];
type T = string
ts
type StringArray = string[];
type T = StringArray[number];
type T = string

要素がユニオン型の配列型に対しても使えます。

ts
type MixedArray = (string | undefined)[];
type T = MixedArray[number];
type T = string | undefined
ts
type MixedArray = (string | undefined)[];
type T = MixedArray[number];
type T = string | undefined

typeof型演算子と組み合わせると、配列の値から要素の型を導くこともできます。

ts
const array = [null, "a", "b"];
type T = (typeof array)[number];
type T = string | null
ts
const array = [null, "a", "b"];
type T = (typeof array)[number];
type T = string | null

タプル型とインデックスアクセス型

インデックスアクセス型はタプル型の要素の型を参照するのにも使えます。タプル型の要素の型を参照するには、ブラケット記法に数値リテラル型を書きます。

ts
type Tuple = [string, number];
type T = Tuple[0];
type T = string
ts
type Tuple = [string, number];
type T = Tuple[0];
type T = string

typeof型演算子と組み合わせると、タプル型の値から要素の型を導くこともできます。

ts
const stateList = ["open", "closed"] as const;
type State = (typeof stateList)[number];
type State = "open" | "closed"
ts
const stateList = ["open", "closed"] as const;
type State = (typeof stateList)[number];
type State = "open" | "closed"
学びをシェアする

TypeScriptのインデックスアクセス型は、プロパティや配列要素の型を参照できる

✏️構文1: オブジェクトの型["プロパティ名"]
✏️構文2: 配列型[number]
🔑keyofと組み合わせると全プロパティの型が取れる
🧲typeofと組み合わせると配列値から要素型が取れる

『サバイバルTypeScript』より

この内容をツイートする