我正在尝试实现一个声明性API,用于使用MDN元数据和TypeScript编写CSS样式。我的目标是将泛型字符串值转换为字符串文本类型,以便以后可以使用它,或者从json元数据代码生成"const“文件,或者动态地使用它。
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;'用法
理想情况下,我们应该生成与cssText属性值类似的字符串文本(在格式上)。
import * as s from './composers'
s.of('button-primary').color('blue').background('white')
// .button-primary { color: blue; background: white; }我为这事挣扎了整整一周。可能是因为我对TypeScript的理解不够好。不管怎样,我想做的是:
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;"我遗漏了什么?
发布于 2022-08-04 18:46:17
我认为你需要通读仿制药:
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);
}
}https://stackoverflow.com/questions/73240788
复制相似问题