In a parent class, I define a method with different parameters: an index in a store or an element, and depending on the parameter, I get the element from the store by its index or just use the given element.
Thus, I use overloading to define these methods:
class Parent<T> {
items: T[] = [];
item: T = {} as T;
applyMethod(index: number): void;
applyMethod(item: T): void;
applyMethod(param: number | T): void {
if (typeof param === 'number') {
param = this.items[param];
}
this.item = param;
}
}
class Child1<T> extends Parent<T> {
// In my application, I actually add an id: string overload.
override applyMethod(param: number | T): void {
// Do something more before calling:
super.applyMethod(param);
}
}
class Child2<T> extends Parent<T> {
override applyMethod(param: number | T): void {
if (typeof param === 'number') {
super.applyMethod(param);
} else {
super.applyMethod(param);
}
}
}
在TS Playground强中也能看到它.
在Child1中,我有一个错误:
No overload matches this call.\
Overload 1 of 2, '(index: number): void', gave the following error.\
Argument of type 'number | T' is not assignable to parameter of type 'number'.\
Type 'T' is not assignable to type 'number'.
Overload 2 of 2, '(item: T): void', gave the following error.\
Argument of type 'number | T' is not assignable to parameter of type 'T'.\
'T' could be instantiated with an arbitrary type which could be unrelated to 'number | T'.(2769
我可以像《子元素2》中所展示的那样解决这个问题,但它非常奇怪/愚蠢.
另一种解决办法是定义applyMethod(param: any): void {}
,而不是number | T
.它是classic 的,这就是我最初所做的,但我发现TS只看到param: any
参数定义,因此我输掉了输入.
我 Select 了另一种方式,拨打了super.applyMethod(param as any);
.至少,输入保留了它们的类型.
有没有其他更优雅的方式?我错过了什么吗?