简体   繁体   English

TypeScript - 是否可以根据模式匹配甚至长度验证字符串类型?

[英]TypeScript - is it possible validate string types based on pattern matching or even length?

Consider the following component, which uses a library called styled-components to create a prestyled Text component:考虑以下组件,它使用一个名为styled-components的库来创建一个预样式化的Text组件:

const StyledText = styled(Text)`
  font-family: Roboto;
  color: ${(props: ITextProps) => props.color || '#000' }; 
`

where ITextProps is:其中ITextProps是:

interface ITextProps {
  color: string;
}

Is there a way to enforce that only valid hex strings are passed to my component?有没有办法强制只将有效的十六进制字符串传递给我的组件?

Ideally the color prop should always match the pattern /#\\d{3}(\\d{3})?/g , a # followed by at least 3 digits and optionally 3 more digits.理想情况下,颜色道具应始终匹配模式/#\\d{3}(\\d{3})?/g ,一个 # 后跟至少 3 位数字和可选的 3 位以上数字。 If that's not possible, then is there a way to at least enforce that the string is either 4 or 7 characters long?如果这是不可能的,那么有没有办法至少强制字符串长度为 4 或 7 个字符?

My research has brought me to a dead end so I'm wondering if anyone on SO might know how I can implement this behavior in TypeScript.我的研究让我走到了死胡同,所以我想知道 SO 上是否有人知道我如何在 TypeScript 中实现这种行为。

Not at compile-time, no. 不在编译时,不。 There is a suggestion to allow regular-expression validated string types, but it's not clear that it will ever be implemented. 建议允许使用经过正则表达式验证的字符串类型,但尚不清楚它是否会实现。 If you want to go to that suggestion and give it a 👍 or describe a compelling use case that isn't already listed, it couldn't hurt (but it probably won't really help either). 如果您想参考该建议并给它一个👍或描述一个尚未列出的引人注目的用例,那么它就不会受到伤害(但也可能实际上没有帮助)。

In lieu of official support, you could: 代替官方支持,您可以:

  • build an enormous union type of every matching string literal, but that is likely prohibitively expensive for such a wide type: 为每个匹配的字符串文字构建一个巨大的联合类型,但是对于如此宽的类型,这可能会非常昂贵:

     type ValidColorString = '#000' | '#001' | '#002' | ... //forget it ☹ 
  • Make a nominal-ish subtype of string and use a user-defined type guard to narrow string values to it... and then jump through all sorts of hoops to use it: 创建一个标称的string子类型,并使用用户定义的类型防护string值缩小到它的范围内...然后跳过各种形式的箍来使用它:

     type ValidColorString = string & { __validColorString: true }; function isValidColorString(x: string): x is ValidColorString { const re = /#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?/g; // you want hex, right? return re.test(x); } 

    Usage: 用法:

     const textProps: ITextProps = { color: "#abc" }; // error, compiler doesn't know that "#abc" is a ValidColorString const color = "#abc"; if (isValidColorString(color)) { const textProps2: ITextProps = { color: color }; // okay now } else { throw new Error("The world has ended"); } 

The latter isn't perfect, but it at least gets you a bit closer to enforcing such constraints. 后者并不完美,但至少可以使您更接近于执行此类约束。

Hope that gives you some ideas; 希望能给您一些想法; good luck! 祝好运!

this is not possible. 这是不可能的。 check discussion on github 查看github上的讨论

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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