Adding properties to an empty object

2019-09-20 08:21发布

问题:

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?