painedpineapple
painedpineapple

Reputation: 1032

Is it possible to have one type's type predicated on the value of another type?

I have a component that accepts a tagType prop. If that tag type is Link or a, I need the link prop to be required. If the tagType is button or input, then the link prop should not be required.

Here's what I have so far, but can't figure out how to set the type of link accordingly:

type linkTagTypes = 'Link' | 'a'
type nonLinkTagTypes = 'button' | 'input'

type tProps = {
  tagType: linkTagTypes | nonLinkTagTypes,
  link: string,
   ...
}

Upvotes: 0

Views: 33

Answers (1)

frontendgirl
frontendgirl

Reputation: 787

One of the possibilities is to use union type, but not for the tagType property, but for the tProps, like following:

type tProps = {
  tagType: linkTagTypes,
  link: string
} | {
  tagType: nonLinkTagTypes,
  link?: string
}

Check this one playground for its usage: Make link required only in one case

Upvotes: 1

Related Questions