1

Lets say I have 2 interfaces.

interface ItemGroup {
    itemDefaults: Partial<Item>
    items: Item[]
}

interface Item {
    price?: number
    size?: string
}

I want to make sure the attribute is provided in default or the Item. Its fine if both are provided, but at least one should be required.

//Should be Valid
[{
    "itemDefaults": {
        "price": 10,
        "size": "L"
    },
    "items": [
        {
            "size": "M"
        }
    ]
}]

//Should be Invalid as both itemDefaults and Item is missing size
[{
    "itemDefaults": {
        "price": 10
    },
    "items": [
        {
            "price": 12
        }
    ]
}]

Is there a way to enforce something like this in TypeScript?

Shuja Shabandri
  • 557
  • 4
  • 12
  • 1
    Isn't this answer what you're looking for? https://stackoverflow.com/a/49725198/3739087 – BorisTB Jan 10 '22 at 10:27
  • No. Its not about x or y property of the same or extended interfaces. Here there are 2 distinct interfaces like a CollectionGroup and the group has a collection of items. – Shuja Shabandri Jan 10 '22 at 10:56
  • `items` is an array. what if one `item` contains an attribute and another one dont. Is it valid or not? – captain-yossarian from Ukraine Jan 10 '22 at 11:39
  • Its fine to have all items with same attributes. One doesn't need to be different from the other, as long as these items include all the required attributes which haven't been specified in the itemDefaults. – Shuja Shabandri Jan 11 '22 at 15:00

0 Answers0