假设我想允许使用十六进制字符串;所以唯一允许的值为 0-9a-f。 TypeScript 有没有办法定义只接受某些字符串的类型字符串? IE。
// valid
const valid: HexString = '123abc';
// invalid
const invalid: HexString = 'ijk';
我知道正则表达式类型定义是一个提案here,想知道是否有办法同时实现这一目标。
仅使用“标称类型”的“不透明类型”,只要您有一个可以使字符串成为十六进制代码的实现,实现如下。
export type Opaque<K, T> = T & { __TYPE__: K };
type HexCode = Opaque<string, "HexCode">
const createHexCode = (str: string): HexCode => {
// implementation that forces string to be hexCode
return str.toString() as HexCode // casting is needed.
}
const test = createHexCode("#333");
const isAssignableString: string = test; // yes anything that is HexCode is still technically a string.
const isAssignableHexCode: HexCode = "standard string" // error
这种模式对于 PositiveInteger 和 PasswordHash 之类的东西也很有用,在这些情况下,您不希望任何人意外地将纯字符串分配给您想要强制人们使用返回 PasswordHash 的函数的值
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)