Home > front end >  How to import nested interfaces in typescript
How to import nested interfaces in typescript

Time:05-21

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

CodePudding user response:

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.

  • Related