我只是想知道 - 这是一种通过 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
那么它是一种定义字符串格式的方法吗?
最佳答案
从 开始,这应该是可能的。 TS 4.1 测试版
现在有一个名为 Template Literal Types 的功能,它看起来像这样(请原谅基本示例):
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-typesPlayground
关于javascript - 是否可以使用 TypeScript 指定字符串格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47176762/