Transform readonly properties into writable properties in TypeScript

I am facing an issue while trying to create a test helper function that simulates document key press events. Here is my current implementation:

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

However, TypeScript throws the following error:

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

I attempted to resolve this by using the following code snippet but ended up with 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);
};

Answer №1

It's puzzling why the error persists even though your approach seems correct. An alternative, more concise version of Mutable can be created for versions 2.8 and above:

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

Check out this demonstration on the TypeScript Playground here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Several arrays within the filteredData (MatTableDataSource) are being utilized

Hey there, I could really use some assistance. I have this data stored in a filteredData variable within a MatTableDataSource. filteredData My goal is to display this data in two separate tables, but I'm encountering issues where nothing is being sh ...

Resetting the timer of an observable in Angular 2

I have a unique service that automatically calls a method every 30 seconds. There is also a button that allows the user to reset the timer, preventing the method from being called for another 30 seconds. How can I make sure that the method does not get cal ...

Creating a React Component in TypeScript that utilizes Promise Objects for data handling

After receiving a Promise type Object as a response, an error has been encountered: Error: Objects are not valid as a React child (found: object with keys { key1, key2, key3 ...}... How can this issue be resolved? // Component.tsx import React, { us ...

What is the best way to declare an array of objects within another array using typescript?

If you need to create an array of objects, the syntax would be: public racks: Rack[]; However, I am looking to create an array that can hold multiple arrays of racks, like this: [ [rack1, rack2, rack3], [rack4, rack5, rack6], [rack7] ] How ca ...

Using TypeScript to dynamically assign types to object properties

As a newcomer to TypeScript, I am in the process of migrating some of my custom components/plugins to TS. One of the challenges I'm facing is setting object properties dynamically when the property name is a variable. I would greatly appreciate a be ...

Unable to execute any actions on object in JavaScript

I currently have two functions in my code: getRawData() and getBTRawData(). The purpose of getBTRawData() function is to retrieve data from Bluetooth connected to a mobile device. On the other hand, getRawData() function takes the return value from getB ...

Parent component interacting with child component

In my application, I have a header component along with registration and login components. The selector of the header component is used in both the login and registration components. There is also a button in the header that displays as a login button if t ...

Expanding ngFor in Angular 2

Is it possible to pass two arguments with ngFor? Here is an example that I would like to achieve: <mat-card *ngFor="let room of arr; let floor of floorArr"> <mat-card-content> <h3>Room Number: {{room}}</h3> <p>Floor ...

How can one interpret the act of "passing" an interface to an RxJS Store using angle brackets?

When working with NgRx and typescript, I often come across this syntax within class constructors: import { Store, select } from '@ngrx/store' class MyClass { constructor(private store: Store<AppState>) { this.count$ = store.pipe(sele ...

Revising Global Variables and States in React

Recently delving into React and tackling a project. I find myself needing to manage a counter as a global variable and modify its value within a component. I initialized this counter using the useState hook as const [currentMaxRow, setRow] = useState(3) ...

Issue encountered: Nuxt 3 fails to locate the useRoute import

Recently, I updated to the latest version of Nuxt and encountered an issue with the useRoute method. Even though it works, I keep getting a "Cannot Find name useRoute" error message. Can anyone help me figure out what might be missing? <script lang=&quo ...

Using TypeScript along with the "this" parameter

Hi there, I'm encountering an issue with the code snippet below. It keeps throwing an error message that says "Property 'weatherData' does not exist on type 'XMLHttpRequest'." The purpose of this code is to display weather informat ...

TestCafe has encountered an issue: "There are no tests available to run. This may be due to either the test files not containing any tests or the filter function being too

Attempting to run automated tests using TestCafe resulted in an error when executing the following command. testcafe chrome testc.ts The specified command was used to test the testc.ts file within my Angular application, with TestCafe installed globally ...

Gain access to TypeScript headers by typing the request (req) object

Is there a way to access headers in a method that is typed with Express.Request? Here's an example code snippet: private _onTokenReceived(req: Express.Request, res: Express.Response): void { const header: string = req.headers.authorizatio ...

From URLSearchParams to HttpParams: A Guide for Angular HttpClient

Facing an issue while updating from Http to HttpClient in a service.ts file on Angular8. I've made the necessary changes from Http and Headers to HttpClient and HttpHeaders, as well as removed '.pipe(map((response) => response.json().response ...

Issues have been identified with the collapse functionality of the Angular 6 Material Tree feature

Recently, I've been working on creating a tree structure to handle dynamic data using Angular material tree component. In order to achieve this, I referred to the code example mentioned below: https://stackblitz.com/edit/material-tree-dynamic Howeve ...

The pagination in React using React Query will only trigger a re-render when the window is in

Currently, I am utilizing React-Query with React and have encountered an issue with pagination. The component only renders when the window gains focus. This behavior is demonstrated in the video link below, https://i.sstatic.net/hIkFp.gif The video showc ...

Ways to disperse items within another item

I have an inner object nested inside another object, and I am looking to extract the values from the inner object for easier access using its id. My Object Resolver [ { _id: { _id: '123456789', totaloutcome: 'DONE' }, count: 4 }, { ...

Tips for synchronizing the value of one field in a reactive form with changes in another field

I have a reactive form below where I'm using a form builder with groups. Fig: https://i.sstatic.net/gdc7p.png Here is the HTML code of the component <div class=""> <form [formGroup]="FeedBack" (ngSubmit)="on ...

Unable to retrieve selected value from Flowbite-React Datepicker due to malfunctioning props change event

I am encountering an issue with extracting the selected value from the Datepicker component in the flowbite-react library while using it with NextJS. The component is being displayed correctly. I attempted the code below, but it does not return anyth ...