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

Chr*_*iss 6 string typescript

如何声明禁止中间有空格的模板文字类型?

这就是我所拥有的,但它允许数字和单位之间有空格。

 type Duration =`${number}${'ms' | `s`}`
    
    let a: Duration = "2000 ms" // should not compile due to ' ' 
    let b: Duration = "2s" // ok
    let c: Duration = "2000ms" // ok
Run Code Online (Sandbox Code Playgroud)

>> typescriptlang.org 游乐场

小智 0

type Digit = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9;
type Unit = 'ms' | 's';
type ValidDuration = `${Digit}${number | ""}${Unit}` & `${number | ""}${Digit}${Unit}`;

let a: ValidDuration = "1 ms" // error as intended
let b: ValidDuration = "2s" // ok
let c: ValidDuration = "2000ms" // ok

const duration = (value: ValidDuration) => value


const x = duration("1ms"); // okay
const y = duration("20000ms"); // okay
const w = duration("1 ms"); // error as intended
const v = duration(" 1ms"); // error as intended
Run Code Online (Sandbox Code Playgroud)

比照。打字稿游乐场。这只是禁止不需要的空间的解决方案。它说明了基本思想,即。检查要解释为数字的子字符串是否以数字开头和结尾(因此禁止前导和尾随空格)。如果应排除不必要的前导零(即禁止“03ms”但允许“0ms”)以及是否应允许自然数以外的数字(例如“5.2ms”或“-7s”),则需要进行更多详细说明。