Search code examples
typescriptdynamic-arrays

Correctly type dynamic array items according to array element's attribute value


Say I have an array like so:

[
    { id: 1, component: "mockup", src: "some-link" },
    { id: 2, component: "header", title: "Some Title", subtitle: "Lorem ipsum..." }
]

I am supposed to render according to the component key's value. How can I tell typescript to expect additional attributes if the component attribute equals to this or not expect this attribute if the component value equals to that? Is this beyond the scope of Typescript?


Solution

  • You can use a discriminated union:

    interface Base {
      id: number;
      component: string;
    }
    
    interface MockupComponent extends Base {
      component: 'mockup';
      src: string;
    }
    
    interface HeaderComponent extends Base {
      component: 'header',
      title: string;
      subtitle: string;
    }
    
    type Component = MockupComponent | HeaderComponent;
    
    const components: Component[] = [
        { id: 1, component: "mockup", src: "some-link" },
        { id: 2, component: "header", title: "Some Title", subtitle: "Lorem ipsum..." },
        { id: 3, component: "other"}, // error
        { id: 3, component: "header", src: "some-link"}, // error
    ];
    

    Playground link