やっていること
変数を使ってJsonファイルのキーから値を取り出したいと思って、カッコの中に変数を入れたところTS7053が出てしまいました。
Jsonファイルをインポートして使うときに設定をしたいです。
手動でやるのもいいですが、自動でできるようにしたいです。
エラーの出るソースコード
TypeScript
1import {hoge} from "./json/hoge"; 2 3type FormValue = { 4 id: string, 5 name: string 6} 7 8const formValue: FormValue = { 9 id: "123", 10 name: "hoge" 11} 12 13const eMail = hoge[formValue.id]; //ここでTS7053
自分での回避策
手動で型定義した別の変数に入れることで回避していますが、このJsonファイルは何度も使うのでこの処理は書きたくありません。
どこかで一括設定して、importした時から適切な型定義がされてほしいです。
TypeScript
1import {hoge} from "./json/hoge"; 2 3type FormValue = { 4 id: string, 5 name: string 6} 7 8type HogeJsonType = { 9 [key: string]: string 10} 11 12const formValue: FormValue = { 13 id: "123", 14 name: "hoge" 15} 16 17const hogeJson: HogeJsonType = hoge 18 19const eMail = hogeJson[formValue.id];
Tsconfigの中味
json
1{ 2 "compilerOptions": { 3 4 /* Projects */ 5 6 /* Language and Environment */ 7 "target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ 8 9 /* Modules */ 10 "module": "commonjs", /* Specify what module code is generated. */ 11 "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ 12 "resolveJsonModule": true, /* Enable importing .json files. */ 13 14 /* JavaScript Support */ 15 16 /* Emit */ 17 "outDir": "./out", /* Specify an output folder for all emitted files. */ 18 19 /* Interop Constraints */ 20 "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ 21 "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ 22 23 /* Type Checking */ 24 "strict": true, /* Enable all strict type-checking options. */ 25 26 /* Completeness */ 27 "skipLibCheck": true /* Skip type checking all .d.ts files. */ 28 }, 29 "include": [ 30 "src/**/*" 31 ], 32 "exclude": [ 33 "node_modules" 34 ] 35} 36
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/08/21 08:13