9

I want to create the following test helper to simulate document key press events:

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);
};

but typescript complains:

TypeError: Cannot set property key of [object KeyboardEvent] which has only a getter

I've tried the following but I get the same error:

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 Answer 1

8

Not sure why you are still getting the error, your approach should work, you can create a less verbose version of Mutable on versions 2.8 and higher:

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);
};

Playground link

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.