Employing a dynamic return type based on a boolean parameter

In the process of developing a library, I am seeking to enhance the accuracy of the Types provided. This would ensure that users of the library are unable to select the incorrect type in a scenario like the one outlined below.

The function described here will return either IPlayerStats or IStatsItem[] based on the true/false value of the convertJSONOutput parameter.

public async getStatsById(
    userId: string,
    timeWindow: TimeWindow = TimeWindow.Alltime,
    convertJSONOutput: boolean = true
  ): Promise<IPlayerStats | IStatsItem[]> {
  // Ommitted
}

The query is:

Is it possible to define a conditional return type that determines which interface will be returned depending on the boolean value of the convertJSONOutput parameter?

Answer №1

If you need to return different types based on a boolean argument, one way to achieve this is through overloads:

function fetchData(id: string, type: DataType, useJSON: true): Promise<Data>;
function fetchData(id: string, type: DataType, useJSON: false): Promise<DataItem[]>;
function fetchData(
    id: string,
    type: DataType = DataType.Default,
    useJSON: boolean = true
  ): Promise<Data | DataItem[]> {

By calling the function with specific arguments, the type of data returned will be determined:

// Promise<Data>
const resultA = fetchData('', DataType.String, true);

// Promise<DataItem[]>
const resultB = fetchData('', DataType.String, false);

The key point here is that each overload specifies the literal values true or false, rather than just the type boolean. The return type is then associated with these values. This relationship is highlighted below.

//                              **** =>        ************
fetchData(useJSON: true): Promise<Data>;

This code is slightly modified for illustrative purposes and assumes the definitions of DataType, DataItem, and Data are already provided:

function fetchData(id: string, type: DataType, useJSON: true): Promise<Data>;
function fetchData(id: string, type: DataType, useJSON: false): Promise<DataItem[]>;
function fetchData(
    id: string,
    type: DataType = DataType.Default,
    useJSON: boolean = true
  ): Promise<Data | DataItem[]> {
  // Ommitted
}

// Promise<Data>
const resultA = fetchData('', DataType.String, true);

// Promise<DataItem[]>
const resultB = fetchData('', DataType.String, false);

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

Having trouble with react-responsive-carousel in Next.js version 13?

I have been following a tutorial to create an eBay clone. One of the steps involves creating a carousel. However, when I add it, the carousel does not transition to the next page. I have attempted to uninstall and reinstall packages, but the issue persists ...

The React error message states that there are no shared properties between the 'Component<P, S>' type and the 'ComponentLifeCycle<P, S>' type

Encountering an error when attempting to bundle my React application, here is the issue I am facing: https://i.sstatic.net/g0yRh.png This is the structure of my @types/react/index.d.ts file: class Component<P, S> implements ComponentLifecycle< ...

There was a build error in npm run due to the inability to destructure the 'store' property from 'useReduxContext2()' when it is null. Additionally, hooks cannot be conditional in Next Js

Next.js with Redux is the framework I am working on, aiming to host the application on Vercel. However, during the local app building process, I'm facing a particular error: The following error occurs - TypeError: Cannot destructure property 's ...

Is it possible for Typescript to provide protection or differentiation based on the presence of a field (undefined / absent) rather than its

Could someone clarify the reason behind why Typescript has the capability to narrow types using the in keyword, but not based on the presence of a non-undefined value? I am in the process of transitioning a significant JavaScript codebase to TypeScript, an ...

Issues with hydrating React local storage hook in custom implementation within NextJS

Currently facing an issue while implementing the localstorage hook in NextJS. The error message I am encountering is: Error: Hydration failed because the initial UI does not match what was rendered on the server.. Any suggestions on what might be causing ...

Facing an issue with the TypeScript error in the Tailwind-Styled-Component Npm package. Any suggestions on how to troub

module.styles.ts File import tw from "tailwind-styled-components"; export const Wrapper = tw.div` bg-green-500 `; export const Link = tw.a` text-blue-500 `; home.jsx File import React from "react"; import { Wrapper, Link } from &qu ...

What is the Typescript compiler utilized by Visual Studio 2015 when compiling on save?

Currently using Visual Studio 2015 Update 3 with TypeScript 2 for VS installed. I have a basic ASP.NET Core MVC web application with a few simple TypeScript files. The project contains a tsconfig.json file in the root folder with "compileOnSave": true. I ...

Issue with `import type` causing parse error in TypeScript monorepo

_________ WORKSPACE CONFIGURATION _________ I manage a pnpm workspace structured as follows: workspace/ ├── apps/ ├───── nextjs-app/ ├──────── package.json ├──────── tsconfig.json ├───── ...

Issue with IN operator functionality in TypeORM when used with MongoDB

My goal is to fetch a list of items using an array of IDs by utilizing the following code: import { In } from 'typeorm'; ...findBy({ _id: In(ids) }) The IDs are predefined upon creation: @Entity() export class Foo { @ObjectIdColumn({ generated ...

TS2786 TypeScript is failing to recognize the UI-Kitten components

Error message on IDE: Error Encountered: 'ApplicationProvider' cannot be used as a JSX component. The instance type 'ApplicationProvider' is not a valid JSX element. The types returned by 'render()' are incompatible betwe ...

NGRX Store: Unable to modify the immutable property '18' of the object '[object Array]'

While attempting to set up an ngrx store, I encountered 7 errors. Error Messages: TypeError: Cannot assign to read only property '18' of object '[object Array]' | TypeError: Cannot assign to read only property 'incompleteFirstPass ...

Pay attention to the input field once the hidden attribute is toggled off

In attempting to shift my attention to the input element following a click on the edit button, I designed the code below. The purpose of the edit is to change the hidden attribute to false. Here's what I attempted: editMyLink(i, currentState) { ...

Backend server encountered an issue with processing punycode

[ALERT] 18:13:52 Server Restarting Prompt: C:\Code\MERN_Projects\podify_app\server\src\db\index.ts has been altered (node:22692) [DEP0040] DeprecationWarning: The punycode module is outdated. Consider utilizing a modern a ...

Utilizing the Double Mapping Feature in React with Typescript

It seems I might be overlooking something, can someone guide me on how to properly double map in this scenario? I'm encountering an error on the second map: Property 'map' does not exist on type '{ departure: { code: string; name: strin ...

Encountered a TypeScript typing error when retrieving data from the Pinia state to populate the template

Having a type error when trying to pass data from the Pinia store to a child component's input field using TypeScript - Error message: 'Property 'storeForm' does not exist on type '{ $: ComponentInternalInstance; $data: {}; $prop ...

Triggering a function when a bound property changes in Aurelia

I'm currently working with a viewmodel that seems to be functioning correctly. @connectTo<State>({ selector: (store) => store.state.pipe(pluck('domain')).pipe(pluck('games')), target: 'games', }) @connectTo& ...

Enhance your Typescript code by incorporating typing for response objects that include both index signatures and key-value pairs

I am grappling with how to properly incorporate typescript typings for the response object received from a backend service: { de49e137f2423457985ec6794536cd3c: { productId: 'de49e137f2423457985ec6794536cd3c', title: 'ite ...

Incorporating dynamic dictionary fields in Reactive and pushing them into an established FormControl

I am attempting to dynamically populate my reactive form with varying fields based on user selection. Here is an example of the fields I have: fields = [{ df_id: 48, df_name: "Phone Number", df_type: "text", ...

The inRequestScope feature seems to be malfunctioning and is not functioning as intended

Need help with using inRequestScope in inversifyJS For example: container.bind<ITransactionManager>(Types.MysqlTransactionManager).to(MysqlTransactionManager).inRequestScope() ... container.get<ITransactionManager>(Types.MysqlTransactionMana ...

The state is not updated correctly by setState when the dropdown values are changed

Currently, I'm facing a situation where I have a dropdown that displays a user's accounts. Based on the selected account, the content of the page should change. I've tried an approach as shown below, but it seems like the setState method is ...