首页 > 解决方案 > Creating a new string literal type based on another

问题描述

The CSS.Pseudo types of csstypes have a bunch of CSS selectors like for ':hover' , ':active' and so on.

Is it possible to create a new type based on CSS.Pseudo, which accepts all the CSS.Pseudo types but with a '&' in front?

For example '&:hover', '&:active' and so on.

I want to be able to do something like

type CSS.Pseudo = ':hover' | ':active' ... etc.

type CssStyle= { [SOMETHINGSOMETHING CSS.Pseudo]: string}

const styles: CssStyle= {
    '@:hover: someCssString, //OK
    ':hover:  someCssString,  //NOT OK
    '&:hov':  someCssString   //NOT OK
}

I've tried a billion things on TS Playground but I feel I'm just not good enough at TS or it's just impossible.

标签: csstypescripttypescript-generics

解决方案


您不能以编程方式执行此操作,至少从 TypeScript 3.5 开始。

之前已经提出过这个建议,并且该建议作为字符串文字键扩充正则表达式字符串文字验证建议的副本而被关闭,这两者都没有特别接近被纳入语言。如果您真的希望看到这种情况发生,您可能想要解决其中一个或两个问题,并给他们一个或可能描述您的用例,如果您认为它比现有的更引人注目。

抱歉,这可能不是您想要的答案,但至少您可以停止尝试让编译器为您执行此操作。祝你好运!


推荐阅读