Transform to a type specialized for a generic type

Is it possible to achieve something similar in TypeScript?

type Something = {...}

interface A extends Something {...}
interface B extends Something {...}

interface MyInterface<T extends Something> {
    method(): T
    anotherMethod(): number | number[]
}

The return type of anotherMethod() is dependent on the generic, so:

  • If T is type A, then anotherMethod() => number
  • If T is type B, then anotherMethod() => number[]

For example:

const myObjA: MyInterface<A> = {}
myObjA.anotherMethod() // ==> returns a number

const myObjB: MyInterface<B> = {}
myObjB.anotherMethod() // ==> returns an array

Does this question make sense?

Thank you, Fran

Answer №1

Of course, you have the option of utilizing conditional types for this purpose.

interface MyInterface<T extends Something> {
    method(): T
    anotherMethod(): T extends A ? number : number[]
}

declare const myObjectA: MyInterface<A>
const x = myObjectA.anotherMethod() // number

declare const myObjectB: MyInterface<B>
const y = myObjectB.anotherMethod() // number[]

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

Create interfaces for a TypeScript library that is available on npm for export

I have a project in TypeScript that I am packaging as a library to be used by both JavaScript and TypeScript projects. After compiling, I upload the .js and .d.ts files to npm. The main.ts file exports the following: interface MyInterface{ // ... } clas ...

Angular 2: Sending an HTTP GET request with custom headers and parameters

I have been encountering difficulties while attempting to retrieve data from a Stardog triple store into Angular. Despite successfully accessing the service using curl with matching headers and parameters, I am unable to replicate this functionality with ...

Aurelia: The passing down of views and view-models

In the process of developing an Aurelia app, I am tasked with creating functionality that allows users to display various lists for different resources. These lists share common features such as a toolbar with search and refresh capabilities, along with a ...

Can one validate a single route parameter on its own?

Imagine a scenario where the route is structured as follows: companies/{companyId}/departments/{departmentId}/employees How can we validate each of the resource ids (companyId, departmentId) separately? I attempted the following approach, but unfortunate ...

React - Component continuously updates during form input

I am facing an issue where as I type in the login form modal, the entire component is re-rendering and causing me to only be able to type 1 or 2 letters before it resets. This is a problem that I have not encountered before. I attempted to factor out the ...

Preserving type information while dynamically adding functions to an object

Within my functions.ts file, I have defined 2 functions. Each of these functions accepts an api object and returns a function with varying argument types, numbers, and return types. export function f1 (api: Api) { return function (a: number): number[] { ...

The scope of the inferred type parameter in the generic TypeScript function is overly broad

I'm currently working on creating a function that takes in another function (a React component) as an argument and then returns a related function. My goal is to define specific requirements for the input function, ensuring that it accepts certain pr ...

Encountering an issue with TypeScript after applying a wrapper to a Material-UI button - specifically, the error message states that the type '{ children: string; color: "light-green"; }' is lacking certain properties

I'm currently working on creating wrapped components using MUI (@material-tailwind/react) within the environment of Next.js 14. However, I've run into a typescript error specifically in the MaterialButton component. Type '{ children: string; ...

Is there a method to globally import "typings" in Visual Code without having to make changes to every JS file?

Is there a method to streamline the process of inputting reference paths for typings in Visual Studio Code without requiring manual typing? Perhaps by utilizing a configuration file that directs to all typings within the project, eliminating the need to ...

Unable to locate the identifier 'Annotorious'

Currently utilizing NextJS with TypeScript The following script has been added: <Head><link href="/css/bindingbox.min.css" rel="stylesheet"></link><script async type="text/javascript" src="/scripts/an ...

Determining Refresh Status in Angular Application

Does Angular provide a method to determine if the browser has been refreshed? I need to verify whether the page has been refreshed or not, as I want to run a function only when the value is false. In my ngOnInit function, I have the following code: pageIs ...

Reading files from multiple sources using Angular's FormArray

I am facing an issue with uploading multiple images from different inputs. I have a form set up with a formArray to add a new input each time the "Add file" button is clicked. this.designForm = this.fb.group({ newFiles: this.fb.array([ this.f ...

Locate a user within an array in Angular 5 by inputting a specific character into a textarea before initiating the search

I'm currently facing a situation with my textarea component... <textarea [(ngModel)]="message" id="commentBox" placeholder="Add your comment here..."></textarea> Additionally, I have a user list that retrieves data from an external API l ...

What are the constants that TypeScript compiles at runtime?

I'm in the process of developing a TypeScript library that needs to support both Node and Browser environments. Currently, I have been compiling my code twice using tsc with different targets for each environment, and it seems to be functioning correc ...

What steps are involved in compiling a library without using Ivy?

After compiling my library, I navigated to dist/my-library and encountered the following error message: ERROR: Attempting to publish a package compiled with Ivy, which is not permissible. Prior to publishing, delete and re-build the package without us ...

What could be causing the error I encounter when attempting to send JSON in a GET request?

Currently, I am utilizing Angular 10 in my project. I am attempting to send an object in a GET request, so I decided to convert it to JSON: getData(dataPlan: Data): Observable<Response<InfoType[]>> { return this.client.get<Response< ...

Using Dynamic Imports in Angular 6 Libraries

After creating a sample Angular 6 Library using the Angular CLI, I have the basic structure with the library "my-lib" and the sample app "test-lib" for testing purposes. Within the library, I am looking to implement dynamic imports. Specifically, I have a ...

Issue with optional generic in Typescript union not functioning as intended

I am facing a challenge with a type that requires an optional generic. In my case, if the generic G is provided, a new property of type G must be included. However, I encountered an issue while trying to implement this in a function: interface Message { ...

Ways to dynamically link a JSON response object to an entity?

In my ng2 implementation, I have a user.service.ts file that calls a REST service and returns JSON data. The code snippet below shows how the getUser function retrieves the user information: getUser(id: number): Promise<User> { return this.http. ...

Ways to confirm non-null values and bypass the row if it is

I have been attempting to compare 2 dates in order to appropriately display data in a table. I have tried the following approach: ${this.dateToCompare.getTime()} > ${row.CreateDate.getTime()} However, there is an issue where CreateDate has a null value ...