Home > Blockchain >  How to define an extension function that operates on type V in Map<K,V[]> in Typescript?
How to define an extension function that operates on type V in Map<K,V[]> in Typescript?

Time:09-26

I want to extend the prototype of Map of type Map<K,V[]> with a function called pushIntoKey(key: K, value:V). What it does is simply initialise an array at a given key when it does not exist, and push the value V into it. I have trouble figuring out the correct declaration statement. Here is my attempt:

declare global {
    interface Map<K, V[]> { //error here, V[] as generic is not allowed
        pushIntoKey(key: K, value: V): void
    }
}

Object.defineProperty(Map.prototype, "pushIntoKey", {
    value: function<K,V>(key: K, value: V): void {
        const self = this as Map<K,V[]>
        if (!self.get(key))
            self.set(key, [])
        this.get(key).push(value);
    }})
export {}

CodePudding user response:

The problem is there is no guarantee V is going to be an array. What you can do is:

interface Map<K, V> 
{
    pushIntoKey(key: K, value: V extends Array<infer T> ? T : never): void
}
  • Related