What causes a compilation error to occur when a mapped type is invoked inside a class?

Below is a code snippet for review.

An error occurs when calling the get method within the class, but works fine when called outside. Any thoughts on why?

type DefinedKeys<T> = keyof {
  [K in keyof T as undefined extends T[K] ? never : K]: K
}

class MyAbstractClass {
  get<K extends keyof this & DefinedKeys<this>>(key: K): this[K] {
    return this[key];
  }
}

class MyClass extends MyAbstractClass {
  foo: string = "ok";
  optional?: string;

  test() {
    this.get('foo'); // Doesn't work 
  }
}

const instance = new MyClass();
const yepItsWorks: string = instance.get("foo"); // Ok

TS Playground

Answer №1

My theory is that within test, the execution context is ambiguous.

TypeScript correctly assumes that you might call the method with a different this using instance.test.call(otherThis) or something similar. It works when you explicitly type this.

class MyClass extends MyAbstractClass {
  foo: string = "ok";
  optional?: string;

  test(this: MyClass) {
    this.get('foo'); // Now it works
  }
}

However, there is some inconsistency - the following should also bind this, but it does not behave as expected:

class MyClass extends MyAbstractClass {
  foo: string = "ok";
  optional?: string;

  test = () => {
    this.get('foo'); // Doesn't work 
  }
  
}

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

Creating dynamic text bubble to accommodate wrapped text in React using Material-UI (MUI)

I am currently developing a chat application using ReactJS/MUI, and I have encountered an issue with the sizing of the text bubbles. The bubble itself is implemented as a Typography component: <Typography variant="body1" sx={bubbleStyle}> ...

Applying TPS rate to existing API endpoints at the method level within API Gateway using AWS CDK

I have successfully set up a UsagePlan and connected it to an API stage with CDK. However, I am having difficulty implementing method throttling at the API stage for a specific resource path. Despite searching online, I have not been able to find a satis ...

Which is the optimal choice: subscribing from within a subscription or incorporating rxjs concat with tap?

After storing data in the backend, I proceed to retrieve all reserved data for that specific item. It is crucial that the data retrieval happens only after the reservation process to ensure its inclusion. Presented with two possible solutions, I am cont ...

What is the significance of incorporating react context, createContext, useContext, and useStore in Mobx?

In my Typescript application, I rely on Mobx for persistence and have created a singleton class called MyStore to manage the store: export class MyStore { @observable something; @observable somethingElse; } export myStore:MyStore = new MyStore(); ...

A script object must only permit one property at a time

I am unfamiliar with TypeScript and I have an object named obj with 3 properties: a, b, c. However, it is important to note that b and c cannot exist together in the same object. So, my object will either be: obj = { a: 'xxx', b: 'x ...

The function signature '(newValue: DateRange<dateFns>) => void' does not match the expected type '(date: DateRange<unknown>, keyboardInputValue?: string | undefined) => void' as per TypeScript rules

I'm currently utilizing the MUI date range picker from https://mui.com/x/react-date-pickers/date-range-picker/. Here's my code snippet: <StaticDateRangePickerStyled displayStaticWrapperAs="desktop" value={valu ...

What is the best way to bundle a TypeScript package along with its dependencies for seamless integration with various Next.js projects on a local environment

Currently, I am immersed in a project with the following arrangement: / # repository root /core # A local, unpublished npm package used by both projectA and projectB /projectA # A Next.js app /projectB # Another Next.js app In my setup, I gene ...

There was an error linking the module "electron_common_features" which caused the Electron react test to fail

I recently developed a React Electron application using the electron-react-boilerplate template. I also added the @electron/remote package and made changes to the test case. However, upon running the command npm test, an error message stating No such modul ...

WebStorm is unable to detect tsconfig paths

Currently, we are facing an issue with WebStorm identifying some of our named paths as problematic. Despite this, everything compiles correctly with webpack. Here is how our project is structured: apps app1 tsconfig.e2e.json src tests ...

How to effectively filter a JSON array using multiple keys?

I need help filtering my JSON data by finding the objects with key 'status' equal to 'p' within the lease array. I attempted to use the following function, but it did not achieve the desired result: myActiveContractItems.filter((myActiv ...

Union types can be used to constrain generic type parameters in Typescript

I'm working on a function uniqueIds(first: any[], second: any[]): number[] { let prop = first[0] instanceof Owner ? "OwnerId" : "BankId"; return _.unique( _.map( first, o => ...

Steps for converting an observable http request into a promise request

Here is a link to my service file: This is the TypeScript file for my components: And these are the response models: I am currently facing difficulties with displaying asynchronously fetched data in my component's TypeScript file using an Observabl ...

What is the reason for my Firestore listener consistently retrieving data from the server despite having offline persistence enabled?

Incorporating Firebase JavaScript Modular Web Version 9 SDK into my Vue 3 / TypeScript application. My understanding is that when utilizing real-time listeners with offline persistence in Firestore, the process should proceed as follows: Upon initializat ...

Encountering difficulties importing in Typescript and ts-node node scripts, regardless of configuration or package type

I am facing a challenge with my React Typescript project where multiple files share a similar structure but have differences at certain points. To avoid manually copying and pasting files and making changes, I decided to create a Node script that automates ...

I am having trouble getting ngFor to properly render my accessible data. Whenever I attempt to use it, it ends up breaking my code. Can someone please

When using *ngFor to iterate through data, everything appears to be working fine until attempting to access nested data within an object inside another object. For example: { "tvshow": [ { "id": "value", "time": { "clock": "valu ...

What purpose does the pipe method serve in RxJS?

It seems like I understand the basic concept, but there are a few unclear aspects. Here is my typical usage pattern with an Observable: observable.subscribe(x => { }) If I need to filter data, I can achieve this by: import { first, last, map, reduce, ...

What is the cause of the error message "property 'map' is undefined"?

I am currently working on a service that looks like this: public getUsers() { return this.httpClient.get(environment.BASE_URL + `api/all`); } In my component, I have implemented the ngx-bootstrap table to display the user data. import { Component, OnI ...

express-typescript-react: The frontend bundle file could not be located (404 error)

Currently, I am in the process of developing a full stack application that utilizes Express (written in Typescript) and React. One key component of my development setup is webpack, which I'm using to bundle both the backend and frontend parts of the a ...

I am experiencing an issue with mydaterangepicker and primeng where it is not displaying properly in the table header. Can anyone assist me with this

I am attempting to integrate mydaterangepicker () with primeng turbotable (since primeng calendar does not meet the requirements), but I am having trouble with its display. Could you please assist me with some CSS code or suggest an alternative solution? ...

Is that possible to prevent the use of the & symbol in Angular 4 HTTP requests?

Using an HTTP request to save data in my database. The code snippet I used is: const form = '&inputdata=' + myinput + '&rf_date=' + rf_date; return this.http.post(this.rootUrl, form, {headers : this.reqHeader}); In thi ...