lundi 29 avril 2019

How to write "K extends keyof T" in a generic class and use K then

I want to create a class, which gets an object as type parameter and then uses the type as a type of a property in that class, so that I can only set and get values, if that key exists in that object.

I create an interface, lets call it IStorage. A class Storage should implement iStorage and store values based on if the key exists in the given object.

interface iStorage<T, K extends keyof T> {
    getField(k: K): T[K];

    setField(k: K, v: string | number | object): T[K];

    render(): void;
}

class Storage<T, K extends keyof T> implements iStorage<T, K> {
    private fields: { [key: K]: string | number | object };

    public getField(k: K): T[k] {
        return this.fields[k];
    }

    public setField(k: K, v: string | number | object): T[k] {
        return (this.fields[k] = v);
    }
}


let storage = new Storage<{name: string, type: number}>();


I want fields in Storage to match the the generic defintion (I think T[K]), but typescript says that key must be of type string or number, so this is not working as expected. In my interface I would like to say, that the second parameter of setFormField is also T[K]. I also think, that my type definition is repetitive. Typescript wants me to give a seconds argument too, which makes sense to me, but I don't want to write K extends keyof T everytime on a function, nor could I then use it as a property type.

Tried quiet a lot, but couldn't get it to work.. I'm a bit lost actually, since I'm trying this for several hours now. Never had to do with generics before, so please be gentle on me. :D

Hope someone could give me a helping hand.




Aucun commentaire:

Enregistrer un commentaire