代码之家  ›  专栏  ›  技术社区  ›  Nick Grealy

如何获取并集对象一侧的类型?

  •  0
  • Nick Grealy  · 技术社区  · 3 年前

    我试图辨别第三方库返回的值的类型。不幸的是,这种类型是不受歧视的联盟的左手边,是匿名的(即没有标记)。

    参见以下示例:

    // given an anonymous return type from a non-discriminated union...
    const someFn = function(): ({ colour: string, flavour: string } | Error) {
        return { colour: 'blue', flavour: 'blue' }
    }
    
    // how do I extract the left hand side type?
    type Flavour = FlavourOrError[0]
    
    1 回复  |  直到 3 年前
        1
  •  0
  •   Nick Grealy    3 年前

    (TIL)我通过使用 ReturnType 来自函数。

    然后使用 Extract 以获得左手边类型。

    如果有人知道更好的方法,请告诉我!

    // 1. get the return type of the function...
    type ReturnUnion = ReturnType<typeof someFn>
    
    // 2. extract the left hand side type, using a sample field...
    type LeftHandSideType = Extract<ReturnUnion, { colour: string }>
    
    // 3. later, use duck typing...
    const value = someFn()
    if (typeof (value as LeftHandSideType).colour !== 'undefined') {
        // do something with it...
    }
    
        2
  •  0
  •   mochaccino    3 年前

    我不明白为什么你不能使用“常规JavaScript”的方式来检查返回的值是否是一个错误:

    const value = someFn();
    
    if (!(value instanceof Error)) {
        // do something with it...
    }
    

    这同样有效,无需使用 ReturnType Extract 。但是,如果返回类型为 someFn 在实际代码中更复杂,则可能更希望使用 ReturnType 具有 摘录