DaraJ
DaraJ

Reputation: 3036

Conditional props in TypeScript

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?

Upvotes: 0

Views: 1115

Answers (2)

Martin
Martin

Reputation: 6136

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

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

Upvotes: 4

theodorc
theodorc

Reputation: 46

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

Upvotes: 1

Related Questions