Conditional generic type in return type with Typescript

How can I condition the generic return type when a value is not present?

type Foo = {};

class Bar<P extends Foo> {
    static make<P extends Foo>(a?: P): Bar<P> {
        return new Bar();
    }
}

Bar.make() // returns Bar<Foo>

However, I would like to achieve something like this:

class Bar<P extends Foo> {
    static make<P extends Foo>(a?: P): Bar<P extends undefined ? never : Foo> {
        return new Bar();
    }
}

Bar.make() // returns Bar<never>
Bar.make({}) // returns Bar<Foo>

Answer №1

To ensure proper functionality, it is important to set the default type as never.

type Foo = {test: number}; // An example implementation of foo used in test cases below

class Bar<P extends Foo> {
  // By allowing P to extend from Foo and setting never as the default
  static make<P extends Foo = never>(a?: P): Bar<P> {
    return new Bar();
  }
}

const t1 = Bar.make(); // Results in Bar<never>
const t2 = Bar.make({ test: 2 }) // Generates Bar<{test: 2}> (subtype of Foo)
const t3: Bar<Foo> = Bar.make({ test: 2 }); // Outputs Bar<Foo> (explicit casting to Bar<Foo>)
const t4 = Bar.make({ bazz: 0 }); // Error in typing, { bazz: 0 } cannot be assigned to Foo

Follow this TypeScript Playground link for a demonstration of the various scenarios.

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

I'm feeling lost when it comes to rendering these components using styled-components in reactjs

Include the BarItem and BarItemSelect components inside the link when the condition is true, both styled with a specific CSS class. Currently, these are two separate components... I'm unsure how to achieve this const S = { BarItem: styled.a` pos ...

Error: Cannot access Angular 5 Title service at this time

When attempting to change the page title using BrowserModule, I encountered an issue. I added the BrowserModule and Title in the application module as shown here: https://angular.io/guide/set-document-title However, in a child module where I tried to add ...

Is it recommended to exclude the NGXS NgxsLoggerPluginModule for production deployments?

When developing, it's common to use the following imports: import { NgxsReduxDevtoolsPluginModule } from '@ngxs/devtools-plugin'; import { NgxsLoggerPluginModule } from '@ngxs/logger-plugin'; Is it recommended to remove these imp ...

The viewport width in NextJS does not extend across the entire screen on mobile devices

I'm currently tackling a challenge with my NextJS Website project. It's the first time this issue has arisen for me. Typically, I set the body width to 100% or 100vw and everything works smoothly. However, upon switching to a mobile device, I not ...

Definition of Promise resolve type in Visual Code's d.ts file

Need help with: // api.js export function getLayout(){ return axios.get('/api/layout').then(res => res.data) } // api.d.ts declare interface JSONResponse { meta: object, data: Array<Field> } export declare function getLayout ...

react-i18next - The function call does not match any overload when the specified type is `string`

I am currently utilizing react-i18next in conjunction with React and TypeScript. Interestingly, when I attempt to load a property using a string literal and type inference, everything works seamlessly. However, once I specify the type as string, an error i ...

How can I configure a mocked dependency in Jest to return a specific value in a function?

I am currently working on simulating a mongoose model to facilitate unit testing for an express controller. To keep things simple, I've removed all unnecessary code and provided below the specific scenario I'm dealing with. Here's the snippe ...

Monitor and compile numerous directories simultaneously in TypeScript (monorepo)

I've been searching far and wide online for a solution to my problem, but unfortunately, I haven't come across anything useful yet. Essentially, I am in need of a tool or method that will allow me to kick off TypeScript file Watching/Compiling in ...

Issue encountered when compiling Vue 3 with TypeScript and Webpack Encore: Vue Router's $route is missing

I've been grappling with setting up vue-router's $route in my shims.vue.d.ts file to avoid getting an error on the this scope. Whenever I try to access this.$route.params.paymentId, I keep receiving a type error: TS2339: Property '$route&apo ...

Transferring Information Between Components

After logging into my login component, I want to pass data to my navbar component but unfortunately, my navbar content does not update. The navbar component is located in the app-module while the login component is in a separate module. I attempted to us ...

When using the Angular Material table with selection enabled, the master toggle functionality should always deselect the

I made modifications to the original Angular Material Table example - Stackblitz. In my version, when some rows are selected and the master toggle is clicked, all selected rows should be deselected (similar to Gmail behavior). The functionality works, but ...

Is it possible to eliminate a parameter when the generic type 'T' is equal to 'void'?

In the code snippet below, I am attempting to specify the type of the resolve callback. Initially: Generic Approach export interface PromiseHandler<T> { resolve: (result: T) => void // <----- My query is about this line reject: (error: a ...

Facing issues updating the parent state value while using NextJs with React

I recently started working with NextJS and React, and I'm using trpc along with useQuery to fetch a list of users. After fetching the user list, I need to filter it based on the user's name. Below is a snippet of the code I've been working ...

Is it possible to inject a descendant component's ancestor of the same type using

When working with Angular's dependency injection, it is possible to inject any ancestor component. For example: @Component({ ... }) export class MyComponent { constructor(_parent: AppComponent) {} } However, in my particular scenario, I am tryin ...

Utilize an alias to define the SCSS path in an Angular-CLI library project

I am in the process of developing a library project using angular-cli. I have been following the guidelines outlined in the angular documentation. This has resulted in the creation of two main folders: one is located at ./root/src/app, where I can showcase ...

Ways to enhance a component by incorporating default properties in React/TypeScript

I am looking to enhance a React/TS component (specifically the @mui/x-data-grid DataGrid) by populating the classes prop with my own application classes. Initially, I thought about creating a new component called CustomDataGrid like this: import React fro ...

What are the reasons for the inability to send form-data in Postman?

Encountering an issue when trying to send form-data in postman as Sequelize returns an error: value cannot be null However, everything works fine when sending a raw request with JSON. Have tried using body-parser and multer, but no luck. This is my inde ...

Angular 6 - Receiving @Input causes output to multiply by 4 instead of displaying just once

In my Angular project, I have two components set up. Here is the code for both: app.component.ts: import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styl ...

Comparing two arrays in Angular through filtering

I have two arrays and I am trying to display only the data that matches with the first array. For example: The first array looks like this: ["1", "2" , "3"] The second array is as follows: [{"name": "xyz", "id": "1"},{"name":"abc", "id": "3"}, ,{"name ...

Unexpected behavior: ng2-dragula modelDrop event leading to undefined array

Struggling to figure out the issue with this code. As shown in this GIF, when dragging a div from one container to another, the object disappears and the array becomes undefined. https://i.stack.imgur.com/TELyc.gif Here is the code snippet: Main View.ht ...