Home > Mobile >  reusing typescript object in an array of object
reusing typescript object in an array of object

Time:10-27

How would you type this nested array of object?

const myItem: Items[] = [{
    id: 1,
    text: 'hello',
    items: [{
        id: 1,
        text: 'world'
    }]
}]

I could do this

interface Item {
    id: number
    text: string
}

interface Items {
    id: number // avoid this duplication?
    text: string // avoid this duplication?
    items: Item[]
}

but I wish to get rid of the duplication. If the item has a lot more properties it doesn't look good.

https://www.typescriptlang.org/play?#code/JYOwLgpgTgZghgYwgAgJKQLbIN4ChkHLAAmAXMiAK4YBG0 hkAHmOQM5hSgDmuAvrlyhIsRCnQQMbHAwIlyVWtGQB6FcjgA3APYlkYABbBpxSgAcANsARwwwbSAD8s-RBbtOPVeq27i oxNzKxs7B2dCIkw2cgkMAG0AXX5BBAcOZAwATzjY6KTkAF5keLxI WQARgAaF2ZWZAByAwgLC21G2vLo8lKXcrIqrsjGNwbGgHdtKAtiRpc ZMWgA

CodePudding user response:

That's exactly what extends is made for:

interface Items extends Item {
    items: Item[]
}

Playground

  • Related