#3326Medium

BEM style string

The Block, Element, Modifier methodology (BEM) is a popular naming convention for classes in CSS. Master advanced TypeScript type manipulation in this medium-level challenge on TypeScriptPro.

In this medium-level challenge, you'll implement BEM<B, E, M> which generates BEM-style CSS class name strings from a block, an array of elements, and an array of modifiers.

Challenge Instructions: BEM style string

Medium

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).

Change the following code to make the test cases pass (no type check errors).

ChallengeSolution
type cases = [
  Expect<Equal<BEM<'btn', ['price'], []>, 'btn__price'>>,
  Expect<
    Equal<
      BEM<'btn', ['price'], ['warning', 'success']>,
      'btn__price--warning' | 'btn__price--success'
    >
  >,
  Expect<
    Equal<
      BEM<'btn', [], ['small', 'medium', 'large']>,
      'btn--small' | 'btn--medium' | 'btn--large'
    >
  >,
]

Pro Challenge

Unlock 102+ medium, hard, and extreme challenges to master advanced TypeScript.

One-time payment. Lifetime access.

Detailed Explanation

type BEM<
  B extends string,
  E extends string[],
  M extends string[]
> = `${B}${E extends [] ? '' : `__${E[number]}`}${M extends [] ? '' : `--${M[number]}`}`

How it works:

This challenge helps you understand template literal types combined with indexed access types and union distribution, and how to apply these concepts in real-world scenarios.

This challenge is originally from here.

Share this challenge

Learn the Concepts