TypeScript:模板文字类型不排除空格

shyt4zoc  于 2023-11-20  发布在  TypeScript
关注(0)|答案(1)|浏览(146)

如何声明一个禁止空格的模板文字类型?
这是我的,但它允许数字和单位之间的空格。

  1. type Duration =`${number}${'ms' | `s`}`
  2. let a: Duration = "2000 ms" // should not compile due to ' '
  3. let b: Duration = "2s" // ok
  4. let c: Duration = "2000ms" // ok

字符串

typescriptlang.org

l2osamch

l2osamch1#

  1. type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
  2. type Unit = 'ms' | 's';
  3. type ValidDuration = `${Digit}${number | ""}${Unit}` & `${number | ""}${Digit}${Unit}`;
  4. let a: ValidDuration = "1 ms" // error as intended
  5. let b: ValidDuration = "2s" // ok
  6. let c: ValidDuration = "2000ms" // ok
  7. const duration = (value: ValidDuration) => value
  8. const x = duration("1ms"); // okay
  9. const y = duration("20000ms"); // okay
  10. const w = duration("1 ms"); // error as intended
  11. const v = duration(" 1ms"); // error as intended

字符串
这只是一个解决方案,以禁止不必要的空格。它说明了基本思想,即检查子串被解释为数字是否以数字开始和结束(因此禁止使用前导和尾随空格)。如果不需要前导零,(即禁止“03 ms”但允许“0 ms”),以及是否应允许自然数以外的数字(例如“5.2ms”或“-7s”)。

展开查看全部

相关问题