[Typescript] Tips: Make accessing objects safer by enabling 'noUncheckedIndexedAccess' in tsconfig

The "noUncheckedIndexedAccess" is the most awesome config option you've never heard of. It makes accessing objects a lot safer, and also powers up TypeScript's inference on objects.

export const myObj: Record<string, string[]> = {};

myObj.foo.push("bar") // no error

 

Add  "noUncheckedIndexedAccess": true to tsconfig.json, 

TS is smart enough if you do:

export const myObj: Record<string, string[]> = {};
if (!myObj.foo) {
  myObj.foo = [];
}
myObj.foo.push("bar"); // fine again

 

posted @ 2022-10-18 01:33  Zhentiw  阅读(31)  评论(0)    收藏  举报