3

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 Answer 1

4

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;
Sign up to request clarification or add additional context in comments.

1 Comment

This is no longer true since Typescript version 2.2 (github.com/Microsoft/TypeScript/milestone/34?closed=1) released 2017.02.07- specifically github.com/Microsoft/TypeScript/issues/12596. You can now do banana.haveToPeel = true;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.