TypeScript条件类型和typeof

时间:2018-12-04 16:59:13

标签: typescript conditional-types

因此,我得到了这段代码,该代码检查从多个AnyOfTheAbove常量中构建type string的情况:

const IT_COULD_BE_THIS = 'something';
const OR_THAT = 'something else';
const OR_EVEN = 'the other thing';

export type AnyOfTheAbove =
    | typeof IT_COULD_BE_THIS 
    | typeof OR_THAT 
    | typeof OR_EVEN;

我很想写

export type AnyOfTheAbove = GetTypeof<
    | IT_COULD_BE_THIS 
    | OR_THAT 
    | OR_EVEN
>;

或类似。我觉得我可以使用条件类型来完成此任务。但是到目前为止,我的所有尝试都燃烧不了。这可行吗?

1 个答案:

答案 0 :(得分:2)

不可能,因为该类型将不接受typeof之前的运行时对象。

如果真的不是为每个对象编写typeof,则可以在函数调用中包装所有对象,然后使用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,但是其中一种意味着伪造的运行时调用,因为另一种方案只是将数组包装在函数调用中以正确推断类型。

没有一个能真正保存字符或简化可读性。