它是
不可能
typeof
. (类和枚举除外)
如果真的是关于不写作的话
类型
对于
每个对象
,你可以包装
所有对象
函数调用
那么
一旦
类型
:
使用伪函数
// No value produced at runtime, but infers union type statically
function unionType<T>(...arr: T[]): T { return null as unknown as T }
const IT_COULD_BE_THIS = 'something'
const OR_THAT = 'something else'
const OR_EVEN = 'the other thing'
// Extract types from function call
type AnyOfTheAbove = typeof AnyOfTheAbove
const AnyOfTheAbove = unionType(
IT_COULD_BE_THIS,
OR_THAT,
OR_EVEN
)
这意味着运行时调用(只返回
null
),但允许绕过限制。
使用元组
// You need to specify `string` to infer each string correctly:
// https://github.com/Microsoft/TypeScript/issues/26158
function tuple<T extends string[]>(...t: T) { return t }
const IT_COULD_BE_THIS = 'something'
const OR_THAT = 'something else'
const OR_EVEN = 'the other thing'
// Extract types from function call
type AnyOfTheAbove = typeof AllOfTheAbove[number]
const AllOfTheAbove = tuple(
IT_COULD_BE_THIS,
OR_THAT,
OR_EVEN
)
事实上,这两种解决方案都使用Tuple,但其中一种方案意味着一个虚假的运行时调用,因为另一种方案只是在函数调用中包装数组以正确推断类型。
编辑日期:2019年8月26日
enum AllEnum {
IT_COULD_BE_THIS,
OR_THAT,
OR_EVEN,
}
// Static type
type All = keyof typeof AllEnum
// Access all strings at runtime
const allAtRuntime = Object.keys(AllEnum)