インデックスアクセス型 (indexed access types)
TypeScriptのインデックスアクセス型(indexed access type)は、プロパティの型や配列要素の型を参照する方法を提供します。
tstypeA = {foo : number };typeFoo =A ["foo"];
tstypeA = {foo : number };typeFoo =A ["foo"];
インデックスアクセス型の構文
インデックスアクセス型は、型に対してブラケット表記法を使います。
tsオブジェクト型["プロパティ名"];配列型[number];
tsオブジェクト型["プロパティ名"];配列型[number];
オブジェクトの型とインデックスアクセス型
インデックスアクセス型にはユニオン型も使えます。
tstypePerson = {name : string;age : number };typeT =Person ["name" | "age"];
tstypePerson = {name : string;age : number };typeT =Person ["name" | "age"];
keyof型演算子と組み合わせると、オブジェクトの全プロパティの型がユニオン型で得られます。
tstypeFoo = {a : number;b : string;c : boolean };typeT =Foo [keyofFoo ];
tstypeFoo = {a : number;b : string;c : boolean };typeT =Foo [keyofFoo ];
もしもオブジェクトの型に存在しないプロパティ名を指定すると、コンパイラが警告を出します。
tstypeAccount = {name : string };typeProperty 'password' does not exist on type 'Account'.2339Property 'password' does not exist on type 'Account'.T =Account ["password" ];
tstypeAccount = {name : string };typeProperty 'password' does not exist on type 'Account'.2339Property 'password' does not exist on type 'Account'.T =Account ["password" ];
配列型とインデックスアクセス型
配列型の要素の型を参照するのにもインデックスアクセス型が使えます。要素の型を参照するには、配列型に[number]をつけます。
tstypeStringArray = string[];typeT =StringArray [number];
tstypeStringArray = string[];typeT =StringArray [number];
要素がユニオン型の配列型に対しても使えます。
tstypeMixedArray = (string | undefined)[];typeT =MixedArray [number];
tstypeMixedArray = (string | undefined)[];typeT =MixedArray [number];
typeof型演算子と組み合わせると、配列の値から要素の型を導くこともできます。
tsconstarray = [null, "a", "b"];typeT = (typeofarray )[number];
tsconstarray = [null, "a", "b"];typeT = (typeofarray )[number];
タプル型とインデックスアクセス型
インデックスアクセス型はタプル型の要素の型を参照するのにも使えます。タプル型の要素の型を参照するには、ブラケット記法に数値リテラル型を書きます。
tstypeTuple = [string, number];typeT =Tuple [0];
tstypeTuple = [string, number];typeT =Tuple [0];
typeof型演算子と組み合わせると、タプル型の値から要素の型を導くこともできます。
tsconststateList = ["open", "closed"] asconst ;typeState = (typeofstateList )[number];
tsconststateList = ["open", "closed"] asconst ;typeState = (typeofstateList )[number];
学びをシェアする
TypeScriptのインデックスアクセス型は、プロパティや配列要素の型を参照できる
✏️構文1: オブジェクトの型["プロパティ名"]
✏️構文2: 配列型[number]
🔑keyofと組み合わせると全プロパティの型が取れる
🧲typeofと組み合わせると配列値から要素型が取れる
『サバイバルTypeScript』より