typescript使readonly属性可写

时间:2018-06-05 15:29:15

标签: typescript

我想创建以下测试助手来模拟文档按键事件:

export const simulateKeyPress = (key: string) => {
  var e = new KeyboardEvent('keydown');
  e.key = key;
  e.keyCode = e.key.charCodeAt(0);
  e.which = e.keyCode;
  e.ctrlKey = true;

  document.dispatchEvent(e);
};

但是打字稿抱怨:

  

TypeError:无法设置[object KeyboardEvent]的属性键   只是一个吸气剂

我已经尝试了以下但我得到了同样的错误:

type Mutable<T extends { [x: string]: any }, K extends string> = { [P in K]: T[P] };

export const simulateKeyPress = (key: string) => {
  var e = new KeyboardEvent('keydown');
  (e as Mutable<KeyboardEvent, keyof KeyboardEvent>).key = key;
  (e as Mutable<KeyboardEvent, keyof KeyboardEvent>).keyCode = e.key.charCodeAt(0);
  (e as Mutable<KeyboardEvent, keyof KeyboardEvent>).which = e.keyCode;
  (e as Mutable<KeyboardEvent, keyof KeyboardEvent>).ctrlKey = true;

  document.dispatchEvent(e);
};

1 个答案:

答案 0 :(得分:3)

不确定为什么你仍然会收到错误,你的方法应该有效,你可以在版本Mutable及更高版本上创建一个不那么冗长的2.8版本:

type Mutable<T> = { -readonly [P in keyof T ]: T[P] };

export const simulateKeyPress = (key: string) => {
    var e: Mutable<KeyboardEvent> = new KeyboardEvent('keydown');
    e.key = key;
    e.keyCode = e.key.charCodeAt(0);
    e.which = e.keyCode;
    e.ctrlKey = true;

    document.dispatchEvent(e);
};

游乐场link