模板文字类型检查 模板文字

2024-01-24

我很好奇 Typescript 4.1 中新的模板文字支持是否可以实现以下功能:

export type LogDateType = `${number}.${number}.${number}` | `${number}.${number}` | `${number}`

我发现如果我对字符串进行类型检查,那么这是有效的2002 or 2002.5.12但在类型检查时失败,例如:

`${fourDigitYear}`

与错误Type 'string' is not assignable to type 'LogDateType'.

除了检查纯字符串之外,还有其他方法可以完成这项工作吗?


Issues: #41732 https://github.com/microsoft/TypeScript/issues/41732 and #41631 https://github.com/microsoft/TypeScript/issues/41631

断言它为const

export type LogDateType = `${number}.${number}.${number}` | `${number}.${number}` | `${number}`

const fourDigitYear = "2000";

const foo: LogDateType = `${fourDigitYear}` as const;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

模板文字类型检查 模板文字 的相关文章

随机推荐