Expanding a Typescript generic class by adding abstract methods

Struggling to expand an abstract generic class and encountering issues with extending certain methods.

Take a look at this:

abstract class A<T,K> {

    protected abstract upload<S>(item: T): S
    protected abstract download(item: T): K

}

class B<T, K > extends A<T, K>{

    protected upload(item: T):string {
        return 'hello'
    }
    protected download(item: T): number{
        return 1

    }

}

The error message when extending the upload method in class B is:

Property 'upload' in type 'B<T, K>' cannot be assigned to the same property in base type 'A<T, K>'.
  Type '(item: T) => string' cannot be assigned to type '<S>(item: T) => S'.
    Type 'string' cannot be assigned to type 'S'.

when extending the download method in class B:

Property 'download' in type 'B<T, K>' cannot be assigned to the same property in base type 'A<T, K>'.
  Type '(item: T) => number' cannot be assigned to type '(item: T) => K'.
    Type 'number' cannot be assigned to type 'K'.
      'number' can be assigned to the constraint of type 'K', but 'K' could be instantiated with a different subtype of constraint '{}'.

Typescript Playground Link

Answer №1

Both functions in the B class have limitations.

The final code structure may vary, but this is a possible representation:

abstract class A<T,K> {

    protected abstract upload<S>(item: T): S
    protected abstract download(item: T): K

}

class B<T, K > extends A<T, K>{

    protected upload<S>(item: T): S {
        // return something of type S
    }

    protected download(item: T): K {
        // return something of type K
    }

}

Interactive Example

Issues with your implementation:

upload cannot return a specific type like

string</code because it should return <code>S
, a generic parameter of the function. This means its type will be specified at the function call.

download can't return a fixed type like

string</code since it's supposed to return <code>K
, a generic parameter of the class. The class level parameter is set during instantiation.

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

Adjust the size and color of text in Chart.js using Angular 5

Why does the font color in chartjs appear as light gray and not print when you want to do so from the page? I tried changing the font color of chartjs in the options attribute, but it didn't work. How can I change the font color in chartjs angular? ...

Error in browsers when declaring an interface in Angular

Currently, I'm enrolled in an online Angular course to brush up on my skills. However, during one of the initial classes, I encountered an error while declaring an interface. interface face{ name: string; address: string; } The error message ...

Choose a single entity from the ngrx store and display it in a separate template

I have been working on a blog application that utilizes ngrx for state management. Currently, there are two main objects stored in the application: { "posts": [...], "users": [...] } Now, I am looking to create a separate component spe ...

Using EventEmitter for Component Communication in Angular 2

I have a duo of components: AppComp and SimulationComp AppComp consists of a single function : createEmptyPromise() { return Promise.resolved('') } and it showcases the following html structure : <simulation-comp (simu)='createEm ...

What is the method for inserting an object into a jsonArray in TypeScript?

I am trying to add an object to existing JSON data in TypeScript. I am new to TypeScript and have created an array variable called jsonArrayObject, which contains a boolean[] type. This jsonArrayObject holds a contactModel object with properties like fname ...

Show the new elements added to an array in Angular without the need to refresh the page

I'm facing an issue where data added to an array is not being displayed on the browser, even though I can see it in the console. How can I ensure that the newly added data shows up without refreshing the screen in Angular? user.component.ts UserData: ...

Issue TS2315: Type 'ElementRef' does not support generics

While attempting to integrate @angular/materials into my application, I encountered a successful compilation with the following error messages: webpack: Compiled successfully. ERROR in node_modules/@angular/material/button-toggle/typings/button-toggle.d.t ...

The parameter "disabled=false" is not functioning properly in TypeScript 2.1

Struggling to deactivate a field by accessing the element ID in TypeScript 2.1. Came across this syntax for TypeScript 1.5, but unfortunately, it doesn't seem to work in 2.1. Any assistance would be greatly appreciated. ( document.getElementById(&apo ...

Creating React components with TypeScript: Defining components such as Foo and Foo.Bar

I have a react component defined in TypeScript and I would like to export it as an object so that I can add a new component to it. interface IFooProps { title:string } interface IBarProps { content:string } const Foo:React.FC<IFooProps> = ({ ...

Load Angular template dynamically within the Component decorator

I am interested in dynamically loading an angular template, and this is what I have so far: import { getHTMLTemplate } from './util'; const dynamicTemplate = getHTMLTemplate(); @Component({ selector: 'app-button', // templat ...

Can you explain the distinctions between QueryBuilder, find, and findOne in TypeORM?

In my typeorm query, I initially used the query builder like this: getManager().CreateQueryBuilder(class_name_from_entity_file, 'xyz').select('column_name').where('active_status=1').execute() While this method gave me the des ...

Waiting for the function to complete within an if statement

When attempting a test, I encountered an issue where the function does not wait for the database request to be made. It seems like the function initially returns undefined, and only after the request is completed it returns true or false causing the test t ...

The issue encountered is a Type Error, as the function crypto.randomUUID() is

Everything is running smoothly with my Next.js app on http://localhost:3000/. To enhance the experience, I made an update to my hosts file. 127.0.0.1 customdomain.local After connecting to http://customdomain.local:3000/, I encountered an error in my cli ...

Setting a default value dynamically in a `select` control can be done by using JavaScript to

Upon subscribing to the HTTP server for data retrieval, my select control in Angular framework gets loaded with the received data. My objective is to set a default value that comprises three values from the server object separated by slashes ("/"), which r ...

Top method for allowing non-component functions to update Redux state without the need to pass store.dispatch() as a parameter

As I work on my first ReactJS/redux project, I find myself in need of some assistance. I've developed a generic apiFetch<T>(method, params) : Promise<T> function located in api/apiClient.ts. (Although not a React component, it is indirect ...

Troubles with Jest tests are encountered when using ts-jest in an ES2020/ESNEXT TypeScript project

Currently, I am working on a VueJS project that utilizes ViteJS for transpilation, which is functioning properly. However, when Jest testing is involved alongside ts-jest, the following Jest configuration is used: jest.config.ts import { resolve } from &q ...

Is it feasible to retrieve the component's class name by using the selector name in Angular 2?

Is there a way in Angular 2 to retrieve the class name or reference of a component based on its selector name? @Component({ selector: 'selector-1', template: '<h1>Hello</h1>', }) export class Component1 {} @Component({ ...

Encountering a 404 error when using the NestJS GET function within the service and controller

I am facing an issue with creating simple GET logic. When I test it in Postman, I keep receiving a 404 error. books.service.ts contains the following basic logic: constructor( @InjectRepository(Books) private readonly booksRepo: Repository<Boo ...

What is the best way to generate a random item when a button is clicked?

I'm currently working on a feature in my component that generates a random item each time I access the designated page. While the functionality is set to automatically refresh and showcase a new random item, I am now looking to trigger this action man ...

Jest's it.each method is throwing an error: "This expression is not callable. Type 'String' has no call signatures."

I've been attempting to utilize the describe.eachtable feature with TypeScript, but I keep running into an error message stating: "error TS2349: This expression is not callable. Type 'String' has no call signatures." Below is my code snippe ...