代码之家  ›  专栏  ›  技术社区  ›  John Reilly

TypeScript条件类型和typeof

  •  3
  • John Reilly  · 技术社区  · 7 年前

    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 回复  |  直到 7 年前
        1
  •  2
  •   kube    7 年前

    它是 不可能 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)
    
    推荐文章