TypeScript类型字符串的特定字符

时间:2019-06-23 01:23:17

标签: javascript typescript

假设我要允许使用十六进制字符串;因此,唯一允许的值为0-9a-f。 TypeScript中是否可以定义仅接受某些字符串的类型字符串?即

// valid
const valid: HexString = '123abc';
// invalid
const invalid: HexString = 'ijk';

我知道Regex类型定义是一个提案here,想知道在此期间是否有办法实现这一目标。

1 个答案:

答案 0 :(得分:2)

仅对于“ OpaqueTypes”或“ Nominal Types”,只要您具有可以将字符串设为HexCode的实现,则实现如下。

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的函数