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.
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).
type BEM<
B extends string,
E extends string[],
M extends string[]
> = `${B}${E extends [] ? '' : `__${E[number]}`}${M extends [] ? '' : `--${M[number]}`}`How it works:
B (block string), E (element string array), and M (modifier string array)E extends [] checks if the element array is empty. If so, no element suffix is added; otherwise __${E[number]} appends each element with the __ separator, where E[number] converts the array into a union of its membersM extends [] similarly checks if the modifier array is empty. If so, no modifier suffix is added; otherwise --${M[number]} appends each modifier with the -- separatorE and M have multiple members, all combinations are generated as a union of stringsBEM<'btn', ['price'], ['warning', 'success']> produces 'btn__price--warning' | 'btn__price--success'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.
Be the first to access the course, unlock exclusive launch bonuses, and get special early-bird pricing before anyone else.
Only 27 Spots left
Get 1 month early access
Pre-Launch discount