Home > Enterprise >  Conditional props in TypeScript
Conditional props in TypeScript

Time:11-29

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?

CodePudding user response:

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

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

CodePudding user response:

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
                }
}
  • Related