You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Typescript中如何为Map<K,V[]>类型定义pushIntoKey扩展函数

错误原因

你编写的声明语句报错,是因为原生Map接口的泛型参数为<K, V>两个独立类型,无法直接将第二个参数固定为数组格式进行全局扩展。

修正后完整可运行代码

declare global {
    interface Map<K, V> {
        // 泛型约束:仅当Map的值类型为T数组时,方法可正常调用
        pushIntoKey<T>(key: K, value: T): this extends Map<K, T[]> ? void : never
    }
}

Object.defineProperty(Map.prototype, "pushIntoKey", {
    value: function<K, T>(key: K, value: T): void {
        const self = this as Map<K, T[]>
        const targetArr = self.get(key)
        if (!targetArr) {
            self.set(key, [value])
            return
        }
        targetArr.push(value)
    },
    enumerable: false // 符合原生方法不可枚举的特性,避免遍历异常
})

export {}

效果验证

// 合法调用:值为数组类型的Map
const arrMap = new Map<string, number[]>()
arrMap.pushIntoKey('count', 1)
arrMap.pushIntoKey('count', 2)
console.log(arrMap.get('count')) // 输出 [1, 2]

// 非法调用:值为非数组类型的Map,TS会直接抛出类型错误
const strMap = new Map<string, string>()
strMap.pushIntoKey('name', '张三') // 类型报错,符合预期

内容的提问来源于stack exchange,提问作者Sophon Aniketos

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 02:54:03