difference between number and generic parameter

Viewed 177

I am writing a class in typescript and don't know how to differentiate between generic and number type parameter. Code example

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: I don't know this problem specifically that y i am writing here instead of searching

2 Answers

I would suggest to go with separate method route as well, but if you are looking for a solution with exact requirements, I think I have found what you are looking for by checking type of an item in array.

Take a look at the code:

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

In order to solve this problem instead defining many functions or constructors (like some programming languages like c++), just define one function or constructor and use switch-case or if-else to handle it. maybe for two different type you want to implement two different functions, but it is so easy to manage, just create two function for each usage, and then call them from your remove() function in switch-case or if-else.

Related