BEM style string

Challenge

The Block, Element, Modifier methodology (BEM) is a popular naming convention for classes in CSS.

For example, the block component would be represented as btn, element that depends upon the block would be represented as btn__price, modifier that changes the style of the block would be represented as btn--big or btn__price--warning.

Implement BEM<B, E, M> which generate string union from these three parameters. Where B is a string literal, E and M are string arrays (can be empty).

Solution

Zur Lösung dieses Problem können wir template literal typen nutzen, um eine Vereinigung aus Zeichenketten basierend auf den drei Parametern zu erhalten.

type BEM<
  B extends string,
  E extends string[],
  M extends string[]
> = `${B}${BE<E>}${BM<M>}`;
// ['small', 'medium', 'large'] => '__small' | '__medium' | '__large'
type BE<T extends string[]> = T extends [] ? "" : `__${T[number]}`;
// ['small', 'medium', 'large'] => '--small' | '--medium' | '--large'
type BM<T extends string[]> = T extends [] ? "" : `--${T[number]}`;

References