Variety of returns from shared functions

class Parent { 
  protected info: any;
  
  getInfo(): dataTypeA | dataTypeB {
    return this.info; 
  } 
} 

class A extends Parent { 
  protected info: dataTypeA = getDataTypeA(); 
} 

class B extends Parent { 
  protected info: dataTypeB = getDataTypeB(); 
} 

How can we modify the a.getInfo() and b.getInfo() methods to specifically return dataTypeA and dataTypeB respectively, instead of the current union type dataTypeA | dataTypeB, assuming that a and b are instances of classes A and B?

Answer №1

To allow derived classes to determine the type of data, you can utilize a type parameter in the Parent class:

class Parent<T> {
    protected data: T;

    get(): T {
        return this.data;
    }
}
class A extends Parent<dataA> {
    protected data: dataA = getDataA();
}

class B extends Parent<dataB> {
    protected data: dataB = getDataB();
}

let a = new A();
var da = a.get(); // will be dataA

let b = new B();
var db = b.get();// will be dataB

Take a look at the code in the playground.

If you want to use common members from dataA and dataB in the Parent class, you can apply a type constraint to T. This ensures that the passed type parameter has specific characteristics, allowing you to access its members within Parent:

class Parent<T extends { commonField: string } > { ... }

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

Using TypeScript to define types for passing a React component as an argument to React.cloneElement

I am currently in the process of migrating a React component from JavaScript to TypeScript. Within this component, there is a call to React.cloneElement, where a value received through props is passed in. This particular value happens to be another React c ...

Arrangement of code: Utilizing a Node server and React project with a common set of

Query I am managing: a simple react client, and a node server that functions as both the client pages provider and an API for the client. These projects are tightly integrated, separate TypeScript ventures encompassed by a unified git repository. The se ...

Pipe for Angular that allows for searching full sentences regardless of the order of the words

I am looking to create a search bar that can search for the 'title' from the table below, regardless of the word order in the sentence. I attempted to use a filter pipe to check if the search string exists in the title. I also experimented with ...

What is the most effective method to query Prisma using a slug without utilizing a React hook?

Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post ...

Issue: Execution terminated with error code 1: ts-node --compiler-params {"module":"CommonJS"} prisma/seed.ts

Whenever I run npx prisma db seed, I encounter the following error: Error message: 'MODULE_NOT_FOUND', requireStack: [ '/run/media/.../myapp/prisma/imaginaryUncacheableRequireResolveScript' ] } An error occurred during the execution ...

What happens when the loading state does not update while using an async function in an onClick event?

I'm currently working on implementing the MUI Loading Button and encountering an issue with changing the loading state of the button upon click. Despite setting the state of downloadLoading to true in the onClick event, it always returns false. The p ...

Prohibit the use of screen printing in a modern web application developed with Angular or ReactJS

Is there a way to prevent screen capturing and recording, specifically in regards to progressive web apps? While some mobile applications offer this feature, I am curious about the feasibility of implementing it in progressive web apps without requiring an ...

After updating the file path, the Next.Js module couldn't be located: Module not found – Unable to

After relocating the EmptyTable.tsx file from its original directory at views/forms-tables/tables/react-table/EmptyTable to a new location at components/Tables/EmptyTable, I encountered a persistent issue. Despite updating the import path in my code to mat ...

Using Node.js with Typescript and RedisJSON allows for a powerful and efficient

I've recently started delving into nodejs, typescript, and redis for programming. However, I've encountered an issue with redis: when defining a data interface to be stored in redis, the system throws errors as soon as I try to specify the data t ...

Typescript Angular filters stop functioning properly post minification

I developed an angular filter using TypeScript that was functioning properly until I decided to minify the source code. Below is the original filter: module App.Test { export interface IGroupingFilter extends ng.IFilterService { (name:"group ...

Troubleshooting a Type Parameter Error in React Native TypeScript

I am working on a project in React Native using TypeScript, and I encountered this issue: I am getting the error Argument of type 'GestureResponderEvent' is not assignable to parameter of type 'SetStateAction<string>'.ts(2345) wit ...

Following modification of a UseState Hook, React component fails to trigger a re-render

After researching various solutions to this issue, I have yet to find a definitive answer. In my code, I utilize a useEffect to fetch an array of objects called "nftRewards". The fetching process works correctly as I can see the data in the console. Howev ...

Advanced automatic type inference for object literals in TypeScript

When working with TypeScript, I often declare generic functions using the syntax: const fn: <T>(arg: T)=>Partial<T> While TypeScript can sometimes infer the type parameter of a function based on its parameters, I find myself wondering if t ...

Error: Unable to locate the type definition file for the '@babel' package

I am currently working on a new project and here is the content of my package.json file. { "name": "dapp-boilerplate", "version": "1.0.0", "main": "index.js", "license": "MI ...

Create type definitions for React components in JavaScript that utilize the `prop-types` library

Exploring a component structure, we have: import PropTypes from 'prop-types'; import React from 'react'; export default class Tooltip extends React.Component { static propTypes = { /** * Some children components */ ...

Distinguishing Literal and Parameterized Routes in Angular 6

I've encountered a strange issue that I'm not sure how to handle. In my application, you can either view your public account or create a new one. The Account and CreateAccount modules are standalone and lazy loaded in the routes.ts file. export ...

Specifying the data type of the input being passed into a .css() function within a jQuery ID selector

Currently, I am facing an issue where I need to position an element below a fixed toolbar. The amount of top-padding required for this positioning varies based on the viewport width. To address this, I have created a formula that calculates the percentage ...

Navigating session discrepancies: Combining various social media platforms using Next.js and NextAuth

Recently, I ran into a problem where, upon logging in with Google, I found myself needing access tokens for Twitter and LinkedIn to send out API requests. The issue came about when NextAuth modified my session data to be from either Twitter or LinkedIn ins ...

Angular 2's one-of-a-kind singleton solution

I'm feeling a bit lost when it comes to singleton services in Angular 2. I need a translation service that will be accessible throughout the entire application, and I want to ensure that only one instance of the service exists. My issue arises when tr ...

Potentially null object in react typescript

In my React application with TypeScript, I have completed the implementation of a chart but encountered an error in the following line: backgroundColor: gradientFill ? gradientFill : chartRef.current.data.datasets[0].backgroundColor, T ...