克隆和变异没有任何“自己的” /可枚举属性的只读对象

时间:2019-07-23 20:20:10

标签: javascript typescript clone mapped-types

我正在使用一个库来在单击的元素旁边显示弹出窗口,但是我也在使用事件委托。库需要将ev.target设置为实际单击元素(ev.currentTarget)的事件对象。我正在尝试克隆MouseEvent,但这具有以下特征:

someClickHandler(ev: MouseEvent) {
    Object.keys(ev); //-> ["isTrusted"] (all other properties are on prototype)
    ev.target = ev.currentTarget; //-> Error: cannot assign to readonly property
}

我提出了以下建议,但我正在寻找更好的建议。至少,这可能会对其他人有所帮助(如果这确实是唯一的方法):

  

Playground here

// This removes "readonly" for all props "P" in type "T"
// It also makes all properties optional "?"
type Mutable<T> = {
    -readonly [P in keyof T]?: T[P];
};

// This creates a new type that can have arbitrary string keys
interface IAnyKey<T> {
    [k: string]: any;
}

// Clones a readonly mouse event into a mutable one.
const cloneMouseEvent = (ev: IAnyKey<MouseEvent>): MouseEvent => {
    const toObj: IAnyKey<Mutable<MouseEvent>> = {};

    // tslint:disable-next-line: forin
    for (const prop in ev) {
        toObj[prop] = ev[prop];
    }

    return toObj as MouseEvent;
};

someClickHandler(ev: MouseEvent) {
    Object.assign(cloneMouseEvent(ev), {
        target: ev.currentTarget
    });
}

0 个答案:

没有答案