noPropertyAccessFromIndexSignature
noPropertyAccessFromIndexSignatureはインデックス型のプロパティ参照に[]を必須にするコンパイラオプションです。
- デフォルト:
false - 追加されたバージョン: 4.2
解説
noUncheckedIndexedAccessと同様にインデックス型を持つオブジェクトに対する型評価です。インデックス型に対するアクセスをインデックス記法に強制します。
ドット記法とインデックス記法についてですが、次のようにあるオブジェクトがあるとしてドット(.)でプロパティアクセスをしているものがドット記法、ブラケット([])でアクセスをしているものがインデックス記法です。
tstypeSystemTerms = {en : string;[key : string]: string;};constbutterfly :SystemTerms = {en : "Butterfly",fr : "Papillon",it : "Farfalla",es : "Mariposa",};// dot syntaxbutterfly .en ;// indexed syntaxbutterfly ["en"];
tstypeSystemTerms = {en : string;[key : string]: string;};constbutterfly :SystemTerms = {en : "Butterfly",fr : "Papillon",it : "Farfalla",es : "Mariposa",};// dot syntaxbutterfly .en ;// indexed syntaxbutterfly ["en"];
SystemTermsはnoUncheckedIndexedAccessにて登場した型と同じものでシステムにおける単語、用語のうち英語は担保し他言語の存在は曖昧なものにしています。
tsconsole .log (butterfly .fr );
tsconsole .log (butterfly .fr );
存在が不確かなプロパティへのアクセスについて、ドット記法でアクセスするときに、このオプションを有効にすると次のようなエラーが発生します。
tsProperty 'fr' comes from an index signature, so it must be accessed with ['fr'].4111Property 'fr' comes from an index signature, so it must be accessed with ['fr'].console .log (butterfly .); fr
tsProperty 'fr' comes from an index signature, so it must be accessed with ['fr'].4111Property 'fr' comes from an index signature, so it must be accessed with ['fr'].console .log (butterfly .); fr
このようにインデックス型へのドット記法でのアクセスが禁止されます。