R
R
Roman Yakimchuk2015-05-09 15:09:42
typescript
Roman Yakimchuk, 2015-05-09 15:09:42

Why does defining an object property after defining a variable not work?

There is a code:

interface foo { [property: string]: number }

var bar: foo = { baz: 1 };

bar.bak = 1;

We can define a `baz` property for a variable, but we can't add a `bak` property afterwards because it doesn't fit the interface. At the same time, the compiler does not swear if we want to add a property at the time the variable is defined. There shouldn't be any difference, but the compiler works like this.
How does this work, and is there a solution to get around this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Riim, 2015-05-15
@Rim

Maybe like this:

interface foo { [property: string]: number; bak?: number; }

var bar: foo = { baz: 1 };

bar.bak = 1;

?

V
Vitaly Sivkov, 2015-06-08
@Sivkoff

The structure you are trying to describe is called a dictionary. It does not have such a concept as a property, there is a concept of an index. Accordingly, it is necessary to apply by index, i.e. like this:
If you absolutely need to access it as a property, specify the type as any:

var bar: any = { baz: 1 };
bar.bak = 1;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question