Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typescript make readonly properties writeable

Tags:

typescript

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);
};
like image 482
dagda1 Avatar asked Jun 05 '18 15:06

dagda1


People also ask

How do I change a read-only property in TypeScript?

You can use mapping modifiers to change a readonly property to mutable in TypeScript, e.g. -readonly [Key in keyof Type]: Type[Key] . You can remove the readonly modifier by prefixing the readonly keyword with a minus - .

What is diff between const and read-only properties in TypeScript?

ReadOnly Vs Const KeywordThe value of readonly field can be changed. The value of the const field can not be changed. It cannot be declared inside the method. It can be declared inside the method.

What is the syntax for making a property read-only?

Following is the syntax of defining read-only fields using readonly keyword in c# programming language. readonly data_type field_name = "value"; If you observe the above syntax, we used a readonly keyword to declare a read-only variable in our application.

What is static readonly in TypeScript?

If we mark any property or member as readonly in typescript, the value for that member cannot be changed further. We can only read the value assigned and cannot modify or update.


1 Answers

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

like image 132
Titian Cernicova-Dragomir Avatar answered Oct 09 '22 11:10

Titian Cernicova-Dragomir