Determining the return type depending on an optional generic parameter

I'm encountering difficulty translating the numerous function overloading examples from SO to my specific scenario:

const createAccessor = <T, >(defaultValue: T) => {

    const value = defaultValue

    function fetch(): T;
    function fetch<TPart>(selector?: (obj: T) => TPart) {
        if (selector)
            return selector(value)

        return value
    }

    return { fetch }
}

const obj = createAccessor({
    part1: { a: 1, b : 2 },
    part2: { name: 'Hans' }
})

// Here is how I aim to utilize it:

const fullObject = obj.fetch()              // should return T
const part1 = obj.fetch(o => o.part1)       // should return TPart

(also available on ts-playground)

When I remove the initial overload, the code compiles but the resulting return types are incorrect. What might be the issue here?

Answer №1

The initial problem was that only the first overload of the function was being displayed because the implementation was not included in the public signatures.

To fix this issue, you need to add an overload for the one returning TPart:

function fetch(): T;
function fetch<TPart>(selector?: (obj: T) => TPart): TPart; // <====
function fetch<TPart>(selector?: (obj: T) => TPart) {
    if (selector)
        return selector(value)

    return value
}

Visit the updated playground

The different parts are outlined below:

// First overload signature (part of the public type of the function):
function fetch(): T;
// Second overload signature (also part of the public type of the function):
function fetch<TPart>(selector?: (obj: T) => TPart): TPart;
// Implementation (NOT part of the public type of the function):
function fetch<TPart>(selector?: (obj: T) => TPart) {
    if (selector)
        return selector(value)

    return value
}

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

Ionic 3 and Angular 6: Json Input Ended Abruptly

I've come across numerous discussions about the error I'm experiencing, but none of the solutions seem to apply to my situation. This morning, when I ran my code, I encountered the "Unexpected end of Json Input" error. Interestingly, I hadn' ...

`MongoDb aggregation performance degradation with numerous collections (join)`

I am currently working on a project using the MEAN stack and I have noticed that I am utilizing a significant number of collections in my aggregation, resulting in a heavy reliance on lookup. This has had a negative impact on performance, causing the execu ...

`Managing select tag data in Angular reactive forms`

Having an issue with selecting the gender option from JSON formatted data received from the backend. The gender is displayed as a select tag on the frontend, but it does not pre-select the option that corresponds to the gender value in the JSON data. The b ...

How can you extract the property names of the first object in an array of objects?

I have an array of objects with the following structure and I want to extract the property names of the first object from this array without including the values. The desired result should only be ["Name", "Account", "Status"] ...

The ngAfterViewChecked function seems to be caught in an endless loop

I am facing an issue where the <cdk-virtual-scroll-viewport> starts from the bottom, but I am unable to scroll up. I suspect that this problem is related to the use of AfterViewChecked. Even after trying AfterViewInit, the issue persists. @ViewChil ...

How does using ngFor and ngModel in Angular cause a change in one select to affect others?

I am looking to implement a feature where users can create multiple select dropdowns, choose options for each one, and then aggregate these selections into an array that will be sent to a parent component. My current approach involves using an *ngFor loop ...

When a function is passed as an argument in Typescript, it may return the window object instead of the constructor

I'm still getting the hang of typescript, and I've come across a situation where a function inside a Class constructor is calling another function, but when trying to access this within sayHelloAgain(), it returns the window object instead. With ...

Implementing scrollIntoView() method in Typescript

Currently, I am focused on automating an AngularJS application. Our go-to automation language is TypeScript. My aim is to scroll to a specific element and then click on it. var element = element(by.className('learn-link')); browser.driver.exec ...

Generate a fresh array by filtering objects based on their unique IDs using Angular/Typescript

Hey there, I am receiving responses from 2 different API calls. Initially, I make a call to the first API and get the following response: The first response retrieved from the initial API call is as follows: dataName = [ { "id": "1", ...

There is no overload that matches this call while looping through Node.js process events

Incorporating a certain library automatically includes uncaughtException and unhandledRejection listeners, which I want to remove. Here's the code snippet: ["unhandledRejection", "uncaughtException"].forEach((eventName) => process .listener ...

Error in TypeScript when accessing object using string variable as index

Currently, I am facing a challenge in my project where I am dynamically generating routes and managing them in an Elysia(~Express) application. The issue arises when TypeScript's type checking system fails to index an object using a string variable. S ...

Cyber Platform

I recently encountered a challenge while working on my web project. What are some areas that can be improved? import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import {map} from 'rxjs/op ...

Assigning fields dynamically based on a generic string union concept

My goal is to create a function that can dynamically add fields and functions to an object based on arguments provided. However, I'm encountering an issue where the function does not recognize the types of these dynamic fields. Here's a simple ex ...

Executing Promises in a loop: TypeScript & Angular with IndexedDB

Currently, I am working on a data synchronization service where data is being retrieved from a web service and then stored in IndexedDB. In my TypeScript Angular Service, the code looks something like this: this.http .post(postUrl, postData) .suc ...

Strategies for Dealing with 'No Search Results' in Your Search Functionality

I am currently facing an issue with displaying "No Results Found" when a user utilizes my search feature. The current problem is that "No Results Found" appears immediately on the screen and then disappears while a search query is being processed, only to ...

I have encountered TS 2322 error in a TypeScript code written in React

import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'; import { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider'; import { DatePicker } from '@mui/x-date-pickers/DatePicker'; const StyledTextFi ...

What is the method for throwing errors with NestJS guards without relying on an authentication module?

Are you looking to customize error responses in NestJS guards? import { CanActivate, Injectable, ExecutionContext, NotFoundException } from '@nestjs/common'; import { Observable } from 'rxjs'; import { InjectModel } from '@nestjs/m ...

What is the best way to extract a specific value from a JSON object?

I'm currently working on building a marketplace using Angular. The main marketplace page is already set up and populated with data from a remote JSON file created with mockapi. However, I've encountered an issue when trying to display a single ra ...

Guidelines for releasing Node.js microservice client as a stand-alone package within the repository

For my current web application project, I have chosen to implement the client <-> api <-> [microservices] pattern. To challenge myself, I am developing my microservices in Clean Architecture with node.js using Typescript. Although I have alrea ...

Typescript: create a type similar to keyof but with a particular value type

I have an interface called MyInterface interface MyInterface { field1: boolean, field2: MyType, field3: MyType } In this interface, I want to create a new type that contains only the keys which have values of type MyType. While I know about the key ...