admin 管理员组文章数量: 1086019
Let's say I want to allow a hex string; so the only allowed values would be 0-9a-f. Is there a way in TypeScript to define a type string that only takes certain strings? i.e.
// valid
const valid: HexString = '123abc';
// invalid
const invalid: HexString = 'ijk';
I know Regex type definitions is a proposal here, was wondering if there was a way to achieve this in the meantime.
Let's say I want to allow a hex string; so the only allowed values would be 0-9a-f. Is there a way in TypeScript to define a type string that only takes certain strings? i.e.
// valid
const valid: HexString = '123abc';
// invalid
const invalid: HexString = 'ijk';
I know Regex type definitions is a proposal here, was wondering if there was a way to achieve this in the meantime.
Share Improve this question asked Jun 23, 2019 at 1:23 KoushaKousha 36.4k59 gold badges188 silver badges314 bronze badges1 Answer
Reset to default 8Only with "OpaqueTypes" or "Nominal Types" aslong as you have an implementation that can make a string a HexCode the implementation is as follows.
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
this pattern is also useful for things like PositiveInteger and PasswordHash where you don't want anyone to accidentally assign a plain-string to that value you want to force people to use a function that returns a PasswordHash
本文标签: javascriptTypeScript type string of specific charactersStack Overflow
版权声明:本文标题:javascript - TypeScript type string of specific characters - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/p/1744076435a2529437.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论