在数字模板文字类型中禁止使用字母数字字符

huangapple go评论94阅读模式
英文:

Disallow alphanumeric characters in numeric template literal types

问题

  1. interface Message{
  2. Code: `SLA${number}`;
  3. }

这个类型定义试图将字符串值限制为SLAXXX的形式。
SLA123SLA01000都是有效的值。

负号是数字的一部分,因此像SLA-102SLA0x10这样的输入仍然会通过检查。

我们如何强制代码字段具有SLA前缀,后跟数字字符?

英文:
  1. interface Message{
  2. Code: `SLA${number}`;
  3. }

The type definition attempts to constraint string values to the form of SLAXXX.
With SLA123 and SLA01000 being valid values.

A negative sign is part of a number, thus input such as SLA-102 or SLA0x10 still pass the check.

How can we enforce the code field to have a prefix of SLA followed by only numeral characters?

答案1

得分: 1

以下是代码的翻译部分:

  1. 你可以使用一个辅助函数来完成这个操作:
  2. type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
  3. type OnlyDigits<S> = S extends '' ? unknown : S extends `${Digit}${infer Tail}` ? OnlyDigits<Tail> : never;
  4. type Code = `SLA${Digit}`;
  5. function code<S extends string>(s: `SLA${S & OnlyDigits<S>}`): Code {
  6. return s as Code;
  7. }
  8. const foo = code(`SLA0000011`);
  9. const bar = code(`SLA000x011`); // KO

希望这对你有帮助。

英文:

You can do this with a helper function :

  1. type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
  2. type OnlyDigits&lt;S&gt; = S extends &#39;&#39; ? unknown : S extends `${Digit}${infer Tail}` ? OnlyDigits&lt;Tail&gt; : never;
  3. type Code = `SLA${Digit}`;
  4. function code&lt;S extends string&gt;(s: `SLA${S &amp; OnlyDigits&lt;S&gt;}`): Code {
  5. return s as Code;
  6. }
  7. const foo = code(`SLA0000011`);
  8. const bar = code(`SLA000x011`); // KO

Playground

The helper function here is required to infer the generic.

huangapple
  • 本文由 发表于 2023年2月18日 17:52:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75492503.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定