dagda1
dagda1

Reputation: 28940

typescript make readonly properties writeable

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

Upvotes: 9

Views: 5103

Answers (1)

Titian Cernicova-Dragomir
Titian Cernicova-Dragomir

Reputation: 250386

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

Upvotes: 8

Related Questions