【发布时间】:2019-07-09 20:52:11
【问题描述】:
我正在验证一个字符串:
type Option = 'm' | 'm2' | 'm3' | 'ft' | 'ft2' | 'ft3'
const optionGood: Option = 'm'
const optionError: Option = 'other text' // Type '"other text"' is not assignable to type 'Option'.ts(2322)
这真的很麻烦,因为在真正的解决方案中,选项的数量是一个三位数。我很想创造这样的东西:
type Unit = 'm' | 'ft'
type Suffix = '' | '2' | '3'
// this line is fictional and doesn't work, but shows what I'm trying to accomplish
type Option = `${Unit}${Suffix}`
我尝试使用stringEnum 生成选项:
/** Utility function to create a K:V from a list of strings */
export function stringEnum<T extends string>(array: Array<T>): { [K in T]: K } {
return array.reduce((res, key) => {
res[key] = key
return res
}, Object.create(null))
}
const Options = stringEnum(['m', 'm2'])
// 'm' | 'm2'
type Options = keyof typeof Options
这仅适用于静态数组。如果您尝试将带有数组的变量提供给stringEnum,选项类型将变得简单string 或any 类型:
const options = ['m', 'm2']
const Options = stringEnum(options)
// string
type Options = keyof typeof Options
我有一组要包含在Options 类型中的所有选项,但我不确定如何处理。所以我的问题是,如何从数组中生成联合字符串类型?
我什至开始考虑生成Options.ts 文件的Node 任务(双重编译?)。
【问题讨论】:
-
类型系统不支持进行字符串操作。如果你真的想编译时验证这样的类型,那么生成一个 ts 文件是要走的路。
标签: typescript