使用ts给Object添加方法比如map

195 阅读1分钟

step1.类型声明

在global.d.ts文件中加入如下代码

type valueof<T> = T extends { [key: string | number | symbol]: infer R } ? R : never
interface Object {
    map<Obj extends object, MapFunc extends (obj: valueof<Obj>) => unknown>(this:Obj,mapFunc: MapFunc): { [key in keyof Obj]: ReturnType<MapFunc> }
}

step2.方法实现

在使用.map方法之前实现该方法

Object.prototype.map = function (mapFunc) {
    const _this = this
    return Object.keys(_this)
        .map((key) => ({ [key]: mapFunc(this[key as keyof typeof _this] as valueof<typeof _this>) }))
        .reduce((a, b) => ({ ...a, ...b }), {}) as { [key in keyof typeof _this]: ReturnType<typeof mapFunc> }
}

step3.use it

console.log(({ a: 100, b: 200 }).map(Boolean))