代码之家  ›  专栏  ›  技术社区  ›  Robert Cooper

Typescript返回类型取决于对象参数

  •  0
  • Robert Cooper  · 技术社区  · 5 年前

    如何基于一个函数正确推断返回类型,该函数有一个参数是两种类型的并集?

    我用条件类型尝试了以下操作,但不起作用(请参见typescript错误的内联注释):

    TypeScript Playground

    type Status = 'statusType'
    type GoalActivity = 'goalActivityType'
    
    type Argument = { type: 'status'; status: Status | null } | { type: 'goalActivity'; goalActivity: GoalActivity | null }
    
    const handleReaction = (arg: Argument): Argument extends { type: "status" } ? Status : GoalActivity => {
        if (arg.type === 'status') {
            return 'statusType' // Type '"statusType"' is not assignable to type '"goalActivityType"'.
        } else {
            return 'goalActivityType'
        }
    }
    

    我还尝试了使用一种形式的函数重载来实现箭头函数( as described here ),但这也会导致TypeScript错误,并使用“any”,这将失去函数定义中的大多数键入好处:

    TypeScript Playground

    type Status = 'statusType'
    type GoalActivity = 'goalActivityType'
    
    type HandleReaction = {
        (arg: { type: 'status'; status: Status | null }): Status
        (arg: { type: 'goalActivity'; goalActivity: GoalActivity | null }): GoalActivity
    }
    
    const handleReaction: HandleReaction = (arg: any) => { // Type '"goalActivityType"' is not assignable to type '"statusType"'.
        if (arg.type === 'status') {
            return 'statusType'
        } else {
            return 'goalActivityType'
        }
    }
    

    这个问题类似于 this one ,但区别在于函数参数是一个对象。

    0 回复  |  直到 5 年前
        1
  •  1
  •   tmhao2005    5 年前

    问题

    首先,您没有为参数使用泛型类型,这将导致 typescript 永远不会根据您的输入推断出正确的类型(您可以想象泛型类型是参数, tsc 需要它根据您的输入计算结果)。

    简言之

    const handleReaction = (arg: Argument): Argument extends { type: "status" } ? Status : GoalActivity => { // ... }

    将始终返回 Status | GoalActivity 作为返回类型。

    解决方案

    当然,这里必须使用泛型类型作为参数。我将使用内联解释拆分您的代码:

    type Status = 'statusType'
    type GoalActivity = 'goalActivityType'
    
    type StatusObj = { type: 'status'; status: Status | null };
    type GoalActivityObj = { type: 'goalActivity'; goalActivity: GoalActivity | null }
    
    type Argument = StatusObj | GoalActivityObj;
    
    // Define returned type based on a input argument `T`
    type ReturnType<T> = T extends StatusObj ? Status : GoalActivity;
    
    // Generic type should be used here
    const handleReaction = <T extends Argument>(arg: T): ReturnType<T> => {
        if (arg.type === 'status') {
    
            // Q: Why do we have to cast here?
            // A: Any returned type can't assign to statement of `type ReturnType<T> ...`
            // but luckily `tsc` still allows us to cast back since they are all string literal
            return 'statusType' as ReturnType<T>;
    
        } else {
            return 'goalActivityType' as ReturnType<T>;
        }
    }
    
    推荐文章