【问题标题】:Is it possible to make a complex typeguard function that infers return type based on provided argument?是否可以创建一个复杂的类型保护函数,根据提供的参数推断返回类型?
【发布时间】:2021-04-14 02:50:31
【问题描述】:

假设我有两个工会:

type Animal = "cat" | "elephant"
type Vehicle = "some small vehicle" | "truck"

我想创建一个函数来推断它正在使用哪个联合,然后保护特定联合中的类型 - 类似于:

function isBig(thing: Animal | Vehicle): (typeof thing extends Animal) ? thing is "elephant" : thing is "truck" {
    if(isAnimal(thing)) return thing === "elephant"
    return thing === "truck"
}

这可行吗?甚至合理?

【问题讨论】:

    标签: typescript typeguards


    【解决方案1】:

    你可以用两个函数签名来做到这一点:

    type Animal = "cat" | "elephant"
    type Vehicle = "some small vehicle" | "truck"
    
    function isBig(thing: Animal): thing is "elephant"
    function isBig(thing: Vehicle): thing is "truck"
    function isBig(thing: Animal | Vehicle) {
        if(isAnimal(thing)) return thing === "elephant"
        return thing === "truck"
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-26
      • 2020-02-28
      • 1970-01-01
      • 1970-01-01
      • 2016-05-02
      • 2020-03-09
      • 2020-06-06
      • 1970-01-01
      相关资源
      最近更新 更多