Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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',
    },
];
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading