score:11

I think what you are looking for are intersection types.

Replace this line:

type Props = SamplePropsOne | SamplePropsTwo;

with this line:

type Props = SamplePropsOne & SamplePropsTwo;
  • Intersection types: combine multiple interfaces/types into one

  • Union types: choose one of multiple interfaces/types

EDIT

What you want is not possible (i think). What you could do is destructuring every type in a single line after casting props:

const SampleComponent: React.FC<Props> = props => {
  const { name } = props as SamplePropsOne;
  const { color } = props as SamplePropsTwo;

  return color ? <h1>{color}</h1> : <h1>{name}</h1>;
};

score:15

Before TypeScript will let you read name or color off the union type, it needs some evidence that you're working with the correct type of Props (SamplePropsOne or SamplePropsTwo). There are a few standard ways to provide it with this.

One is by making the union a tagged union by introducing a property to distinguish branches of the union. This type checks just fine:

interface SamplePropsOne {
  type: 'one';
  name: string;
}

interface SamplePropsTwo {
  type: 'two';
  color: string;
}

type Props = SamplePropsOne | SamplePropsTwo;

const SampleComponent: React.FC<Props> = props => (
  props.type === 'one' ? (
    <h1>{props.name}</h1>
  ) : (
    <h1>{props.color}</h1>
  )
);

If you get the cases backwards (as I did when writing this!) then TypeScript will complain.

If the presence of a property is enough to distinguish the types, then you can use the in operator:

interface SamplePropsOne {
  name: string;
}
interface SamplePropsTwo {
  color: string;
}
type Props = SamplePropsOne | SamplePropsTwo;

const SampleComponent: React.FC<Props> = props => (
  'color' in props ? (
    <h1>{props.color}</h1>
  ) : (
    <h1>{props.name}</h1>
  )
);

If determining which type of object you have requires more complex logic, you can write a user-defined type guard. The key part is the "is" in the return type:

function isSampleOne(props: Props): props is SamplePropsOne {
  return 'name' in props;
}

const SampleComponent: React.FC<Props> = props => (
  isSampleOne(props) ? (
    <h1>{props.name}</h1>
  ) : (
    <h1>{props.color}</h1>
  )
);

It's also worth noting that because of the way structural typing works, there's no reason props in your example couldn't have both name and color:

const el = <SampleComponent name="roses" color="red" />;  // ok

If it's important to not allow this, you'll need to use some slightly fancier types:

interface SamplePropsOne {
  name: string;
  color?: never;
}
interface SamplePropsTwo {
  color: string;
  name?: never;
}
type Props = SamplePropsOne | SamplePropsTwo;

The ts-essentials library has an XOR generic that can be used to help construct exclusive unions like this.


Related Query

More Query from same tag