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);
};
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 - .
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With