1
type UrlCellRendererProps = {
    prop1: string;
};

type GroupByCellRendererProps = {
    prop2: boolean;
    prop3: number;
};

type TEST = UrlCellRendererProps | (UrlCellRendererProps & GroupByCellRendererProps)

// this is valid
const a: TEST = {
    prop1: 'url',
}

// this is valid
const b: TEST = {
    prop1: 'url',
    prop2: true,
    prop3: 13
}

// this should be invalid because prop3 is missing
const c: TEST = {
    prop1: 'url',
    prop2: true,
}

console.log(a)

in the example above I have a create a type called TEST which is a union type of two types. How can I enforce the type so that either (prop1 is required) OR (prop1 AND prop2 AND prop3 are required)

Matan Gubkin
  • 3,019
  • 6
  • 25
  • 44
  • 4
    Your last example is valid because it matches `UrlCellRendererProps` by itself. Having an extra property called `prop2` doesn't mean it doesn't match that type. – Etheryte Jun 27 '22 at 17:46
  • You can fix this using an exclusive OR . Look at this answer : https://stackoverflow.com/questions/42123407/does-typescript-support-mutually-exclusive-types. I have created a TS playground to test this : https://cutt.ly/LKS6Wl3 – Tushar Shahi Jun 27 '22 at 18:02
  • The first comment is completely accurate though – Tushar Shahi Jun 27 '22 at 18:02
  • @TusharShahi wow that was exactly what I was looking for. I still could not understand the cause for this behavior of TypeScript. Why would the default union TS behave like this? – Matan Gubkin Jun 27 '22 at 19:51

0 Answers0