使用枚举参数输入重载函数的推断?

时间:2017-06-03 20:43:13

标签: typescript

是否可以使用带有枚举参数的重载函数执行类型推断?例如,假设我正在尝试创建一个返回类型取决于枚举值的工厂函数:

enum Colors {
  Red,
  Green
};

abstract class Box { };
class RedBox extends Box { };
class GreenBox extends Box { };

class BoxFactory {
  static createBox(color: Colors.Red): RedBox;
  static createBox(color: Colors): Box {
    switch (color) {
      case Colors.Red:
        return new RedBox();
      case Colors.Green:
        return new GreenBox();
    }
  } 
}

function makeMeABox(color: Colors) {
  // Argument of type 'Colors' is not assignable to parameter of type 'Colors.Red'
  return BoxFactory.createBox(color);
}

playground

如果我生成一个声明文件,一般的重载甚至都不会出现。但是,如果我删除重载static createBox(color: Colors.Red): RedBox;

,一切都会好的

1 个答案:

答案 0 :(得分:1)

您只缺少一个签名:

class BoxFactory {
  static createBox(color: Colors.Red): RedBox;
  static createBox(color: Colors): Box; // <--- THIS ONE
  static createBox(color: Colors): Box {
    switch (color) {
      case Colors.Red:
        return new RedBox();
      case Colors.Green:
        return new GreenBox();
    }
  } 
}

然后:

let a = BoxFactory.createBox(Colors.Red); // type of a is RedBox
let b = BoxFactory.createBox(Colors.Green); // type of b is Box

code in playground