typescript: allow merge types, include all from first type and include all from second or none

15 views Asked by At

I want to create a type based on BaseProps and ExtraProps. All the ExtraProps' properties should exist or not, so if I add one of them, I should add all other ExtraProps' properties

type BaseProps = {
  prop1: string;
  prop2: number;
};

type ExtraProps = {
  extraPropA: boolean;
  extraPropB: string;
};

type MyType = BaseProps | (BaseProps & ExtraProps);

Usage:

const obj1: MyType = {
  prop1: "value1",
  prop2: 42,
  extraPropB: "someValue" // should fail (no extraPropA)
};

const obj2: MyType = {
  prop1: "value2",
  prop2: 55,
  extraPropA: true // // should fail (no extraPropB)
};

const obj3: MyType = {
  prop1: "value3",
  prop2: 12 // OK, only BaseProps is present
};

const obj4: MyType = {
  prop1: "value4",
  prop2: 555,
  extraPropA: true,
  extraPropB: "someValue" // OK, both extra props are present
};

Playground

0

There are 0 answers