Obtain the specific generic type that is employed to broaden the scope of a

I am working on a class that involves generics:

abstract class Base<P extends SomeType = SomeType> {
  // ...
}

In addition, there is a subclass that inherits from it:

class A extends Base<SomeTypeA> {
  // ...
}

I'm trying to figure out if TypeScript supports a way to determine "What type did class A use when extending Base?"

Essentially, I want something like

type PropType = ExtendedGeneric<A> // SomeTypeA

Answer №1

To extract the type passed to Base, you can utilize a conditional type.

type ExtendedGeneric<T extends Base<any>> = T extends Base<infer P> ? P: never
type PropType = ExtendedGeneric<A> // SomeTypeA

Check out this Playground Link for more examples

For further information on conditional types, refer to this resource

Answer №2

To integrate this function into your foundational code, simply follow these steps:

abstract getStructure(): Constructible<Format>;

You will also need to create a Constructible interface:

export interface Constructible<S> {
    new (data): S;
}

Afterwards, within your A class, include the following implementation:

class A extends Core<SomeTypeA> {
  getStructure(): Constructible<SomeTypeA> {
    return SomeTypeA;
  }
  // ...
}

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

`The error "mockResolvedValue is not recognized as a function when using partial mocks in Jest with Typescript

Currently, I am attempting to partially mock a module and customize the return value for the mocked method in specific tests. An error is being thrown by Jest: The error message states: "mockedEDSM.getSystemValue.mockResolvedValue is not a function TypeEr ...

Implementing query parameters in a Deno controller

I developed a couple of APIs for a Deno Proof of Concept. This is the route implementation: const router = new Router() router.get('/posts', getPosts) .get('/posts/:id', getPostsById) In the second route, I successfully retriev ...

Sorting through a list of strings by checking for a specific character within each string

After spending years dabbling in VBA, I am now delving into Typescript. I currently have an array of binary strings Each string represents a binary number My goal is to filter the array and extract all strings that contain '1' at position X I ...

"Implementing an abstract method in a class by overloading it with a generic type that

// Greetings from the TypeScript Playground, a platform where you can experiment with TypeScript code. type Constructor<T> = new (...args: any[]) => T; class ServiceChecklistResponse { } class AnotherModel { } abstract class AbstractView { ...

Deduce the Prop Component Type by Examining the Attribute Type

I am facing an issue with a component that requires a `labels` attribute. <Component defaultValue={FURNITURE.BED} labels={[ { value: FURNITURE.BED, text: 'Bed', }, { value: FURNITURE.COUCH, text: 'C ...

Can someone show me how to properly set up nested child routes in Angular 2?

My application structure is organized as shown below . ├── photos ├── posts ├── users │   ├── detail │   │   ├── address │   │   ├── family │   │   ├── information │   │   └ ...

Using Angular 6 to Share Data Among Components through Services

I am facing an issue in my home component, which is a child of the Dashboard component. The object connectedUser injected in layoutService appears to be undefined in the home component (home userID & home connectedUser in home component logs); Is there ...

Arrange information in table format using Angular Material

I have successfully set up a component in Angular and Material. The data I need is accessible through the BitBucket status API: However, I am facing an issue with enabling column sorting for all 3 columns using default settings. Any help or guidance on th ...

disappearing of vue event on single file component HTML element

I'm currently working on an ElectronJs project with Electron Forge, using the Webpack + Typescript template project In addition to that, I've integrated Vue and vue-loader for webpack in order to utilize Single File Component (SFC) files: { ...

How can one change the data type specified in an interface in TypeScript?

I am currently diving into TypeScript and looking to integrate it into my React Native application. Imagine having a component structured like this: interface Props { name: string; onChangeText: (args: { name: string; value: string }) => void; s ...

deliver a promise with a function's value

I have created a function to convert a file to base64 for displaying the file. ConvertFileToAddress(event): string { let localAddress: any; const reader = new FileReader(); reader.readAsDataURL(event.target['files'][0]); reader ...

Making if-else statements easier

Greetings! I have a JSON data that looks like this: { "details": { "data1": { "monthToDate":1000, "firstLastMonth":"December", "firstLa ...

What's the best way for me to figure out whether type T is implementing an interface?

Is it possible to set a default value for the identifier property in TypeScript based on whether the type extends from Entity or not? Here's an example of what I'm trying to achieve: export interface Entity { id: number; // ... } @Compon ...

Storing input values in the state using Typescript by default

Upon launching, my activeField state is initially empty. However, when a user focuses on the field, it gets added to the state. I am encountering a warning in Typescript because when I attempt to update the selectionEnd of that field, it tells me: Property ...

Storing data from a collection of interface objects in a string array

Take a look at the following code snippet: import React, {FC} from 'react'; import {useFetchErrors} from "../Api/Api"; import {useLocation} from "react-router-dom"; interface ExecutionTableProps { project_id: number } const ...

Navigating Mixins in Ember CLI Typescript

I'm curious about the best approach for handling mixins in a typed Ember application. While removing mixins from the application is ideal, many addons do not yet support TypeScript. So, how can we effectively utilize Ember Simple Auth's applicati ...

Prevent assigning values to rxjs observables recursively

I am seeking suggestions on how to enhance the code provided below. I will outline the issue and present my current solution, which I aim to refine. The code is written in Angular 4 (TS). herelistOfItems$: Observable<Array<Item>>; // Fetchin ...

Integrating d3.js into an Angular 2 project

Trying to incorporate the d3.js library into a MEAN application using angular2. Here are the steps I've taken: npm install d3 tsd install d3 In mypage.ts file (where I intend to show the d3.js graph) // <reference path="../../../typings/d3/d3.d ...

Struggling to iterate through JSON data in Office Scripts?

My task involves parsing JSON data in Office Scripts to extract the headings and row details on a spreadsheet. While I have successfully fetched the data, I am encountering an error message stating that my information is not iterable at the "for" loop. ...

When using React with TypeScript, there seems to be an issue where using history.push to change the URL results in rendering the 404 page instead

I have gone through all the previous answers but none of them could solve my problem. I am new to React and currently working on a personal project where I use React with TypeScript, Redux, and Material UI. For some reason, when I try to redirect from ins ...