I'm analyzing an Angular code and I came across a type
of a property
of an Interface
named 'Origin' that I don't understand?, Here it is:
export interface Origin {
areaNum?: number;
open?: { [key: string]: any };
}
My first question is what kind of object is that? I thought objects
had one or many key:value
pairs, where the key
is.., well the key :), and the value
can contain any value. This weird type
seems to be an object
but I don't see a key:value
, it just contains an ¿array
?. It seemed to me like if it was array
because of the square brackets, but ¿can an array be the key of an object
? how?. I'm trying to figure out how the property open
would look like when creating an object that uses this Interface
. I don't understand what is this { [key: string]: any };
.
Would you help me understand?, as I'm learning. If possible, may you show me a dummy example object
that uses this open
property
with a valid value
of the above weird type
?. Thanks!
CodePudding user response:
My first question is what kind of object is that?
It's an object that has two optional properties:
areaNum
, a numberopen
, an object using an index signature allowing string indexes: the object can have properties with any string name, and the value of those properties isany
Here's a code example, see comments:
export interface Origin {
areaNum?: number;
open?: { [key: string]: any };
}
let a: Origin = {
areaNum: 42,
open: {}, // <== Valid, an index signature allows there to be no properties
};
if (a.open) {
// You can do this, because `a.open` has an index signature making
// any string is a valid property for it:
a.open["any string you want"] = 42;
// You *can't* do this, because `a` doesn't have an index signature,
// it only has `areaNum` and `open` properties:
a["any string you want"] = 42;
}