首页 > 其他分享 >[Typescript] Tips: Make accessing objects safer by enabling 'noUncheckedIndexedAccess' in

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

时间:2022-10-18 01:44:05浏览次数:65  
标签:noUncheckedIndexedAccess Typescript Make objects accessing myObj foo 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

 

标签:noUncheckedIndexedAccess,Typescript,Make,objects,accessing,myObj,foo,tsconfig
From: https://www.cnblogs.com/Answer1215/p/16801259.html

相关文章