[TypeScript] Type Challenges #3326 - BEM style string

35 阅读1分钟

题目描述

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

题解

// ============= Test Cases =============
import type { Equal, Expect } from './test-utils'

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'>>,
]


// ============= Your Code Here =============
type BEM<
  B extends string,
  E extends string[],
  M extends string[]
> =
  `${B
  }${E extends [] ? '' : `__${E[number]}`
  }${M extends [] ? '' : `--${M[number]}`
  }`
  1. 拼接B

  2. 拼接E

    • E extends [] ? '' : __${E[number]

      • 如果E是空数组:

        • 返回空字符串
      • 如果E是非空数组:

        • 返回__E中每个元素的联合类型拼接的字符串
  3. 拼接M

    • M extends [] ? '' : --${M[number]

      • 如果M是空数组:

        • 返回空字符串
      • 如果M是非空数组:

        • 返回--M中每个元素的联合类型拼接的字符串