[英]How to use function overload with classes in TypeScript?
Given following TypeScript code 给出以下TypeScript代码
class NumberChecker { }
class StringChecker { }
class Component {}
class ComponentChecker { }
class Grid { }
class GridChecker { }
function check(element: number): NumberChecker;
function check(element: string): StringChecker;
function check(element: Grid): GridChecker;
function check(element: Component): ComponentChecker {
if (typeof element === 'number') {
return new NumberChecker();
}
if (typeof element === 'string') {
return new StringChecker();
}
if (element instanceof Component) {
return new ComponentChecker();
}
if (element instanceof Grid) {
return new GridChecker();
}
}
const a = check(2); // a is NumberChecker
const b = check('sdf'); // b is StringChecker
const c = check(new Component()); // c is GridChecker
const d = check(new Grid()); // d is GridChecker
Why c
and d
are both GridChecker
? 为什么
c
和d
都是GridChecker
? I was expecting c
to be ComponentChecker
. 我期待
c
成为ComponentChecker
。
The signature of the actual implementation needs to cover all of the options, in your case, it should be: 实际实现的签名需要涵盖所有选项,在您的情况下,它应该是:
function check(element: number): NumberChecker;
function check(element: string): StringChecker;
function check(element: Grid): GridChecker;
function check(element: Component): ComponentChecker;
function check(element: number | string | Grid | Component) {
// ...
}
Then the type for: 那么类型为:
const c = check(new Component());
Is ComponentChecker
. 是
ComponentChecker
。
But again, only if the different classes don't have the same structure. 但同样,只有不同的类不具有相同的结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.