我只是想知道 - 这是一种通过TypeScript检查字符串是否匹配某些模式的方法。
我不想在运行时进行检查。
//What I have now
public id: string; //can be whatever string
//What I want to see
public id: IdType; //Some type?
id = '0000-0000-0000-0001'//valid
id = 'whatever'//invalid
这是一种定义字符串格式的方法吗?
答案 0 :(得分:1)
从 TS 4.1 beta版起
现在有一个名为“模板文字类型”的功能,它看起来像这样(请以基本示例为例):
type idType = `${number}-${number}-${number}-${number}`
const id: idType = '0000-0000-0000-0001';
https://devblogs.microsoft.com/typescript/announcing-typescript-4-1-beta/#template-literal-types