0

I'm not sure if this is the right place to ask this conditional question, but can we do general types in TypeScript? I often have components like follows:

type Props = {
  title: string
  buttonLabel?: string
  onButtonClick?: () => void
}

So I can optionally provide a string for a button and if it's provided then I also should provide what happens to it on click. However I want onButtonClick to be mandatory if buttonLabel is provided. Some syntax like:

type Props = {
  title: string
  buttonLabel?: string
  onButtonClick<!buttonLabel>: () => void
}

Is this available in Typescript or any other language?

Dara Java
  • 2,410
  • 3
  • 27
  • 52
  • Do you mean https://stackoverflow.com/questions/56949513/typescript-type-of-a-property-dependent-on-another-property-within-the-same-obj? – jonrsharpe Nov 28 '21 at 14:55
  • Kind of. I would like to be able to define it on a per prop basis instead of having to repeat all the types for each conditional type. Although this may be a sign of bad design/I may not know what I'm talking about – Dara Java Nov 28 '21 at 14:59

2 Answers2

4

I would combine a type that omits both with a type that requires both

type Props = {
  title: string;
} | {
  title: string;
  buttonLabel: string;
  onButtonClick: () => void;
}
Martin
  • 5,714
  • 2
  • 21
  • 41
1

You can make buttonLable and onButtonClick be mandatory together by making another object like this if I understood you correctly:

type Props = {
  title: string
  buttonLink?: string
  buttonData?: {label: string
                onButtonClick: () => void
                }
}
theodorc
  • 46
  • 4