使用枚举参数重载函数的类型推断?
问题描述:
是否有可能使用带枚举参数的重载函数执行类型推断?例如,说我想做一个工厂函数返回类型取决于枚举值:使用枚举参数重载函数的类型推断?
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);
}
如果我生成一个声明文件,一般过载甚至不显示向上。但是,如果我删除过载static createBox(color: Colors.Red): RedBox;
,情况很好。
答
你只是缺少一个签名:
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
+0
你的方法很好,谢谢!你能帮助我理解为什么我们需要额外的重载与功能签名相同吗?如果重载,编译器是否不解析主函数签名? –
+1
实际实现的签名不是重载列表的一部分,这意味着在您的代码中只有一个签名(其中'color = Colors.Red'),我的代码为一般情况添加了第二个签名。只是在这种情况下,实现的签名与它匹配。 –
返回类型是从来没有考虑过,甚至像Java静态类型语言的函数签名的一部分和C++ – Dummy