Adding properties to an empty object

回眸只為那壹抹淺笑 提交于 2020-01-07 08:14:07

问题


I have this code

var MY_OBJ = {};
MY_OBJ.test = function(){}

and I'm using Vscode, I get property test not defined. How do I let this be just a warning.


回答1:


This will fix your problem

var MY_OBJ:any = {};
MY_OBJ.test = function(){}



回答2:


Define your object to have a test property:

var MY_OBJ: {test?: Function} = {};

MY_OBJ.test = function() { };

Or, set the property this way:

MY_OBJ['test'] = function() { };

For further type-safety, define MY_OBJ to be an object:

var MY_OBJ: { [propName: string]: any } = {};

This will prevent errors such as MY_OBJ = 14;.

If you intend this object to always have function valued keys, then

var MY_OBJ: { [propName: string]: Function } = {};

will prevent errors such as MY_OBJ['test'] = 14;.

If you're going to use any in the way proposed in the accepted answer, what's the point of using TypeScript in the first place?



来源:https://stackoverflow.com/questions/39792221/adding-properties-to-an-empty-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!