0

It Typescript when I import nested interfaces the predictatext in VS code shows me items in the high level interface but not in the nested one.

There is a [key:string] in the "Example" interface does this mean I cannot use the predictatext for data structures of this sort (even though it will check type safety), or is it just not working as I have set it up incorrectly.

Example

export interface Item {
    id: number;
    size: number;
}
export interface Example {
    name: string;
    items: {
        [key: string]: Item
    };
}

Then file 2

import {Example, Item} from '../utils/interfaces'

const obj = {
    name: "test",
    items: {
        "a": {
            id: 1,
            size: 10
        },
        "b": {
            id: 2,
            size: 34
        }
    }
}

RESULT

The predictertext works for the first level interface but not after that eg

console.log(obj.            // predictatext offers two options: items & names
console.log(obj.items.      // predictatext offers :    NOTHING

1 Answer 1

1

The problem isn't the nested interfaces. The following won't autocomplete either:

interface Example {
   [key: string]: number
}

It can't autocomplete because the key could be anything. Similarly, anything after obj.items. is valid.

If only certain items are allowed, you would have to specify them in the interface.

Sign up to request clarification or add additional context in comments.

2 Comments

Ahh! So All I have to do is persist I just tested it and you are correct. example here eg console.log(obj.items.a.{then I get autocomplete once I fill in a}). Thanks!
I actually hadn't realised that was your question, so I'm glad you figured it out! Btw, I just noticed that the object is const. If the object won't change, you can write as const at the end and you will have autocomplete and type safety for that object in particular, but I don't know if that's actually your case.

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.