我正在用打字本写一个类,不知道如何区分泛型和数字类型参数。代码示例
class Test<T> {
remove(value: T): boolean;
remove(index: number): boolean;
remove(indexOrValue: T|number): boolean {
if (typeof indexOrValue === "number") {
/* What about new Test<number>() */
const index = indexOrValue as number;
this.items.splice(index, 1)
return true;
} else {
const index = this.items.indexOf(indexOrValue as T)
if (index > -1) this.items.splice(index, 1);
return true;
}
return false;
}
}
PS:我不知道这个问题,我在这里写,而不是搜索
发布于 2020-09-24 07:47:09
我也建议使用单独的方法路径,但是如果您正在寻找一个具有确切要求的解决方案,我想我已经通过检查数组中的项的类型找到了您想要的。
看一看代码:
class Test<T> {
items: T[] = [];
remove(value: T): boolean;
remove(index: number): boolean;
remove(indexOrValue: T|number): boolean {
const length = this.items.length;
if (length === 0) {
return false;
}
const isArgumentNumber = typeof indexOrValue === "number";
const isGenericTypeNumber = typeof this.items[0] === 'number';
if (isArgumentNumber) {
if (isGenericTypeNumber) {
// TODO: When input and class both are number
} else {
// TODO: When input is number but class is not
}
} else {
// TODO: When input is not a number
}
}
}
发布于 2020-09-19 22:47:22
为了解决这个问题,而不是定义许多函数或构造函数(比如一些像c++
这样的编程语言),只需定义一个函数或构造函数并使用switch-case
或if-else
来处理它。对于两种不同的类型,您可能希望实现两种不同的函数,但是管理非常容易,只需为每次使用创建两个函数,然后从remove()
函数在switch-case
或if-else
中调用它们。
https://stackoverflow.com/questions/63859304
复制相似问题