基于输入的TypeScript返回类型

时间:2018-06-20 15:28:39

标签: typescript

我具有以下功能:

subtract(sub: number | CalendarWeek): T {
    if (typeof sub === 'number') {
        return new CalendarWeek(...); // Returns a CalendarWeek if sub is a number
    }

    return 1; // Return number if sub is CalendarWeek
}

问题是我需要定义类型T,以便它取决于提供的sub类型。也就是说,如果numbersub,则T为CalendarWeek;如果CalendarWeeksub,则number

2 个答案:

答案 0 :(得分:4)

处理此问题的传统TypeScript方法是使用overloaded functions。在您的情况下,它将类似于:

subtract(sub: number): CalendarWeek;
subtract(sub: CalendarWeek): number;
subtract(sub: number | CalendarWeek): number | CalendarWeek {
  if (typeof sub === 'number') {
    return new CalendarWeek(...); // Returns a CalendarWeek if sub is a number
  }
  return 1; // Return number if sub is CalendarWeek
}

可以想象,在TypeScript 2.8及更高版本中,可以使用conditional types而不是重载来表示这一点,但是它可能比您试图到达这里要先进。

对于感兴趣的各方,该解决方案如下所示:

subtract<T extends number | CalendarWeek>(sub: T): T extends number ? CalendarWeek : number;
subtract(sub: number | CalendarWeek): number | CalendarWeek {
  if (typeof sub === 'number') {
    return new CalendarWeek(); // Returns a CalendarWeek if sub is a number
  }
  return 1; // Return number if sub is CalendarWeek
}

希望有帮助。祝你好运!

答案 1 :(得分:2)

您可以使用多个重载根据参数的类型返回特定类型

function subtract(sub: number): CalendarWeek
function subtract(sub: CalendarWeek): number
function subtract(sub: number | CalendarWeek): number | CalendarWeek {
    if (typeof sub === 'number') {
        return new CalendarWeek(); // Returns a CalendarWeek if sub is a number
    }

    return 1; // Return number if sub is CalendarWeek
}

或者我们可以使用条件类型来达到类似的效果:

function subtract<T extends number | CalendarWeek>(sub: T): T extends number ? number : CalendarWeek
function subtract(sub: number | CalendarWeek): number | CalendarWeek {
    if (typeof sub === 'number') {
        return new CalendarWeek(); // Returns a CalendarWeek if sub is a number
    }

    return 1; // Return number if sub is CalendarWeek
}