3
votes

If I declare an interface in Typescript with a single named property and an index signature, my assumption is that the index signature allows me to add properties to the object without syntax errors.

interface Fruit {
    colour: string;
    [otherProperties: string]: any;
}

This works when I add the properties on declaration so the following compiles OK:

let apple: Fruit = {
    colour: 'green',
    haveToPeel: false
}

but if I extend after creation

let banana: Fruit;
banana.colour = 'yellow';
banana.haveToPeel = true;

then I get a TS error

"[ts] Property 'haveToPeel' does not exist on type 'Fruit'."

I've read around on index signatures but can't get to the bottom of how I allow my objects to be extended dynamically after creation without a TS compile error.

1

1 Answers

4
votes

This is expected behavior.

To use the index signature you need to use the index syntax -- or use the literal assignment which you demonstrate works.

let banana: Fruit;
banana.colour = 'yellow';
banana['haveToPeel'] = true;