Home > database >  Optional property on the first element of an array but required on the others
Optional property on the first element of an array but required on the others

Time:11-23

I would like to define an interface for an array of objects, where all of the objects should have the same structure, with the exception that the first element has one of the properties as optional.

An example of the data stored in the array would look like the following:

const array: Item[] = [{
  value: 'Value1'
},
{
  label: 'Label2',
  value: 'Value2'
},
{
  label: 'Label3',
  value: 'Value3'
},
{
  label: 'Label4',
  value: 'Value4'
}];

My current interface looks like the following:

interface Item {
  label?: string;
  value: string;
}

This means that the label property is optional on all elements of the array, while I want it to be optional on the first one, but mandatory on the rest.

CodePudding user response:

You can use variadic tuple types (Typescript 4.0 ) like so:

interface First {
    label?: string;
    value: string;
}

interface Item {
    label: string;
    value: string;
}

type Items = [First, ...Item[]];

const array: Items = [
    {
        value: 'Value1',
    },
    {
        label: 'Label2',
        value: 'Value2',
    },
    {
        label: 'Label3',
        value: 'Value3',
    },
    {
        label: 'Label4',
        value: 'Value4',
    },
];
  • Related