Skip to content

Commit 77a36b2

Browse files
authored
Add noUncheckedIndexedAccess TypeScript compiler flag (#84)
This PR adds the `noUncheckedIndexedAccess` compiler option to `tsconfig.json`. This flag forces us to check if the values of index signature keys are defined before working with them. For details, see [the `tsc` documentation](https://www.typescriptlang.org/tsconfig/#noUncheckedIndexedAccess). It is no exaggeration to say that much of our object type safety is mere theater without this flag. Without it, the following is valid TypeScript: ```typescript const obj: Record<string, unknown[]> = {} const val = obj['lmao'] val.push('yolo') // no complaint ``` I advocate that we end this insanity now, and enable `noUncheckedIndexedAccess` everywhere. Unsurprisingly, our controllers contain the most violations of this rule, but only about 60 all in all: MetaMask/core#554. The main drawback of enabling this flag is that we have to add non-null assertions or unnecessary if statements to some parts of our code, because TypeScript generally can't map enumerated keys to their objects. For example: ```typescript const obj: Record<string, string[]> = getMyObject() for (const key of Object.keys(obj)) { const val = obj[key] // "val" is: unknown[] | undefined val.push('foo') // error } ``` However, trading convenience for type safety is the value proposition of TypeScript, so that's life, I guess. Fixing the above line and keeping our linter happy is as simple as: ```typescript const obj: Record<string, string[]> = getMyObject() for (const key of Object.keys(obj)) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const val = obj[key]! // Note the postfix bang. "val" is now: unknown[] val.push('foo') // success! } ```
1 parent 453a52d commit 77a36b2

File tree

1 file changed

+1
-0
lines changed

1 file changed

+1
-0
lines changed

tsconfig.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
"moduleResolution": "node",
99
"noEmit": true,
1010
"noErrorTruncation": true,
11+
"noUncheckedIndexedAccess": true,
1112
"strict": true,
1213
"target": "es2017"
1314
},

0 commit comments

Comments
 (0)