0

I am trying to create to type my class with generics and it alays throws me an error

class CustomDataStructure<T> {
    public _data: object;

     constructor() {
        this._data = {};
        }
    public getAndDeleteRandomKey(): void {
        const allExistingKeys = Object.keys(this._data);
        const randomKey = allExistingKeys[Math.floor(Math.random()*(allExistingKeys.length))];
        this.removeItem(randomKey);
    }
   
    public addItem(value: T): void {
        console.log("adding");
        console.log(this._data)
        this._data[value] = new Date().getTime();
    }

    public removeItem(key: T): void {
        delete this._data[key];
    }
}

let ss = new CustomDataStructure<string>();
ss.addItem("hello");
ss.addItem("hello2");

This throws me 2 different errors

  1. parameter of type 'T'.'T' could be instantiated with an arbitrary type which could be unrelated to 'string'.

  2. Type 'T' cannot be used to index type 'object'

am i missing anything here

TypeScriptPlayground

3
  • Why are you using a generic type here? What other possible types would you use to key your data object? Commented Nov 10, 2020 at 20:47
  • Keys can be numbers as well Commented Nov 10, 2020 at 20:50
  • 1
    They can, but ultimately under the hood they get cast to string. Commented Nov 10, 2020 at 20:52

1 Answer 1

1

The reason for this is that the generic T could be also a complex object, e.g. a class instance and you only can use primitive objects as key

const object = {}
object["myKey"] = true // works 
object[new Date()] = true // not works, because is a complex object 

consider using a map, see

Playground

class CustomDataStructure<T> {
    private _data: Map<T, any> = new Map();

     constructor() {}
    public getAndDeleteRandomKey(): void {
        const allExistingKeys = Array.from(this._data.keys());
        const randomKey = allExistingKeys[Math.floor(Math.random()*(allExistingKeys.length))];
        this._data.delete(randomKey);
    }
   
    public addItem(value: T): void {
        this._data.set(value, new Date().getTime())
    }


}

let ss = new CustomDataStructure<string>();
ss.addItem("hello");
ss.addItem("hello2");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.