typescript - 数字和通用参数之间的区别

我正在用 typescript 编写一个类,但不知道如何区分泛型参数和数字类型参数。代码示例

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:这个问题我不是很清楚,我是写在这里而不是搜索

最佳答案

我也建议使用单独的方法路由,但如果您正在寻找具有确切要求的解决方案,我想我已经通过检查数组中项目的类型找到了您正在寻找的东西。

看一下代码:

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
        }
  }
}

https://stackoverflow.com/questions/63859304/

相关文章:

javascript - select2 on select data-select2-id 属性添

gradle - React Native 项目 Android Gradle Fail (Reac

python - 使用 tokenizer.encode_plus 时遇到问题

tensorflow - Keras SavedModel 与 Tensorflow SavedMo

reactjs - CRA typescript环境导出类型时如何解决解析错误

python-3.x - 如何创建 swagger :response that produces

flutter - 如何在 Flutter 中绘制尖三角形边?

javascript - 如何在 react 中的不同组件库之间共享上下文?

javascript - 使用逗号自动格式化数字时如何保留预期的光标位置?

python - 为什么 Keras 不返回 lstm 层中细胞状态的完整序列?