简体   繁体   中英

How to discriminate unions of string literal types?

I'm trying to implement a declarative API for writing CSS styles using MDN metadata and TypeScript. My goal is to cast generic string values to string literal types so I can user it later on, either code-generating "const" files from json metadata or dynamically.

const data = [
  { type: 'at-rule', value: '@media' },
  { type: 'css-property', value: 'color' }
]

const createPrefix = <P extends string>(prefix: P) => <A extends string>(it: A) => `${prefix}: ${it};` as `${P}: ${A}`

const color = createPrefix('color') // works

// usage
const blueText = color('blue')
// const blueText: 'color: blue;'
Usage

Ideally we'd generate string literals similar (in format) to the value of cssText property of a CSSStyleRule .

import * as s from './composers'

s.of('button-primary').color('blue').background('white')
// .button-primary { color: blue; background: white; }

I've been struggling for a whole week with this. Probably I understand TypeScript so badly that I'm trying to do something undoable or felt into a bad practice. Regardless, here's what I'm trying to do:

type AtRule =
  | '@color-profile'
  | '@charset'
  | '@counter-style'
  | '@document'
  | '@font-face'
  | '@font-feature-values'
  | '@import'
  | '@property'
  | '@keyframes'
  | '@viewport'
  | '@media'
  | '@namespace'
  | '@page'
  | '@supports'

const createPrefix =
  <A extends AtRule>(a: A) =>
  <B extends string>(b: B) => {
    return `${a}: ${b};` as const
  }

function getComposer<T extends AtRule>(s: T) {
  const value: T = s
  return createPrefix(value)
}

const data = [{ value: '@charset' }, { value: '@document' }] as const

const prefixes = data.map(d => getComposer(d.value))

const something = prefixes[0]('blue')
console.log(something) // → '@charset: blue;'
// const something: "@charset: blue;" | "@document: blue;"

What am I missing?

I think you need to go through generics:

  const createPrefix = <A extends string>(a: A) => <B extends string>(b: B) => {
    return `${a}:${b}` as `${A}:${B}`
  }
  function getComposer<T extends Prop>(s: T) {
    switch (s.value) {
      case "background":
        return createPrefix<T['value']>(s.value)
      case "color":
        return createPrefix<T['value']>(s.value)
      default:
        return assertNever(s);
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM