Search code examples
javascripttypescripttypescript-typingsreact-typescript

Use one or another interface type in Typescript/React


Having this type:

export interface IMyTypes {
  First: {
    name: string;
    city: string;
    country: string;
    status: string;
  };
  Second: {
    name: string;
    age: number;
    height: number;
  };
}

This must be used in a component but I cannot make it accept both, the props should be First or Second.

I can make it work for First:

import { IMyTypes } from '../my-types';

interface MyComponentProps {
  componentProps: ComponentProps<IMyTypes['First']>;
}

or for the second:

interface MyComponentProps {
  componentProps: ComponentProps<IMyTypes['Second']>;
}

But doesn't work to make it accept one or the other, tried like the following but it isn't correct:

interface MyComponentProps {
  componentProps: ComponentProps<IMyTypes['First' | 'Second']>;
}

Is there a solution to this?


Solution

  • The solution that solves the issue:

    interface MyComponentProps {
      componentProps:
        | ComponentProps<IMyTypes['First']>
        | ComponentProps<IMyTypes['Second']>;
    }