Combine two or more types and tuples in Typescript

Asked

Viewed 40 times

1

In the section below, I have the following types:

// eg.:
type ButtonTypeModifiers = 'is-primary' | 'is-secondary'
type ButtonMarginModifiers = 'has-margin' | 'has-no-margin' | 'has-no-margin-mobile'
type ButtonSizeModifiers = 'is-mall' | 'is-large' | 'is-large-mobile' | 'is-extra-large-mobile'

type ButtonProps = {
  id: string
  // ---> a linha abaixo é onde está o meu desafio <---
  modifiers: [ButtonTypeModifiers, ButtonMarginModifiers, ButtonSizeModifiers]
}

With the code above, I got the following:

<Button id="test" modifiers={['is-primary', 'has-margin', 'is-large']}

But I need something like:

<Button id="test" modifiers={['has-margin', 'is-primary', 'has-no-margin-mobile', 'is-large', 'is-extra-large-mobile']} />

I need to combine several types in tuples within a array. To tuple occupies a position of array and forces me to fill with an option and secure that position, however, in a array I need to use several of my values types.

In short, within one all the values that are in my types Button...Modifiers are eligible to use as value in the property I need type.

1 answer

3


If you want to create a type for a array combining the types you already have, you can do so:

type Modifiers = Array<ButtonTypeModifiers | ButtonMarginModifiers | ButtonSizeModifiers>;

Or, with the alternative syntax:

type Modifiers = (ButtonTypeModifiers | ButtonMarginModifiers | ButtonSizeModifiers)[];

Thus, Modifiers will accept a array with elements of any of the types formed by union.

Learn more about arrays in this documentation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.