Is it true that "Conditional types" are not compatible with actual functions?

Checking out https://www.typescriptlang.org/docs/handbook/2/conditional-types.html

I'm curious as to why this code is not functioning properly?

interface IdLabel {
  id: number
}

interface NameLabel {
  name: string
}

type NameOrId<T extends number | string> = T extends number
  ? IdLabel
  : NameLabel;

function createLabel<T extends number | string>(idOrName: T): NameOrId<T> {
  if (typeof idOrName === 'number') {
    return { id: 1 }
  } else {
    return { name: 'foo' }
  }
}

On the other hand, this code snippet does work according to the documentation example provided. However, it seems pointless as it does not actually return any value...

function createLabel<T extends number | string>(idOrName: T): NameOrId<T> {
  throw "unimplemented";
}

Is it possible that conditional types only function with "type definition"..?

Answer №1

It is not possible to assign a value to an unresolved conditional type, which still relies on a free generic type variable. In such cases, the only solution is to use a type assertion.

Source:

Here are two approaches you can take:

1. Type Assertion

function createLabel<T extends number | string>(idOrName: T): NameOrId<T> {
  if (typeof idOrName === 'number') {
    return { id: 1 } as NameOrId<T>
  } else {
    return { name: 'foo' } as NameOrId<T>
  }
}

2. Overload the Method

function createLabel<T extends number | string>(idOrName: T): NameOrId<T>;
function createLabel(idOrName: number | string): IdLabel | NameLabel {
  if (typeof idOrName === 'number') {
    return { id: 1 }
  } else {
    return { name: 'foo' }
  }
}

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

"An issue has been identified where TSLint and VSCode fail to display red underlines in

I am currently working on a single .ts file where I am experimenting with configuring tslint and tsconfig. To test the configuration, I intentionally added extra spaces and removed semicolons. Despite running the command tslint filename.ts and detecting e ...

The error "ReferenceError: window is not defined" occurs when calling client.join() due to

I am looking to create a video call application using React and Next.js with the AgoraRTC SDK. After successfully running AgoraRTC.createClient(), AgoraRTC.createStream(), and client.init(), I encountered an error when trying to execute client.join(). The ...

Unlocking the potential of deeply nested child objects

I have a recursively typed object that I want to retrieve the keys and any child keys of a specific type from. For example, I am looking to extract a union type consisting of: '/another' | '/parent' | '/child' Here is an il ...

Implementing service injection within filters in NestJS

Looking to integrate nestjs-config into the custom exception handler below: import { ExceptionFilter, Catch, ArgumentsHost, Injectable } from '@nestjs/common'; import { HttpException } from '@nestjs/common'; import { InjectConfig } fro ...

Require a property to be mandatory depending on the value of another property within a generic interface

Looking for a way to have one property affect the others in a react component interface? Here's an example of what I'm trying to achieve: export interface IMyAwesomeComponentProps<T = {}> { className: string defaultPath?: ISomeOthe ...

Using Angular Ionic 3 to apply the disabled attribute

I have a situation in my main.ts where I need to disable a textarea in the HTML if an object is initialized. I've attempted various methods like: ng-attr-disabled="!myObj"; ng-attr-disabled="{myObj!= null}"; and also directly using ng-disabled. I e ...

angular2 and ionic2 encounter issues when handling requests with observable and promises

I am attempting to trigger an action once a promise request has been resolved, but I'm having trouble figuring out how to achieve this. After doing some research, I learned that Ionic2 storage.get() returns a promise, and I would like to make an HTTP ...

Windows drive letter casing error when using Yarn and NextJS

Today, I set up a fresh project using Yarn and NextJS on my Windows computer. When I try to start the project, I encounter an error stating that the casing is "invalid" for the project directory. The specific errors I am facing are: Invalid casing detecte ...

Enhance a subject's behavior by overriding the .next method using a decorator

Currently, I am working on an Angular application where I have numerous Subjects, BehaviorSubjects, and ReplaySubjects as properties in various services. I am attempting to create a TypeScript decorator that can be added to some of these Subjects to enhanc ...

Issue with TypeORM @BeforeInsert causing a field in Entity not to be populated with value

Currently, I am facing an issue where I am attempting to update or insert into a token field before the record is saved. However, when utilizing the @BeforeInsert hook, I encounter the following error: "error": "Cannot read property 'co ...

What might be the underlying reason for Chrome displaying a net::ERR_FAILED error when attempting to make a request from a Vue frontend to a C# API using Axios?

I have a C# Backend+API that I interact with from my Vue Application using axios to make requests. In the C# code, there is an endpoint that looks like this: // GET: api/Timezone public HttpResponseMessage GetTimezoneData() { ...

Displaying Well-Formatted XML in Angular2 Using Typescript

After receiving this XML string from the server: <find-item-command xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" find-method="Criteria" item-class="com" only-id="false" xsi:schemaLocation=""> <criteria> <criterion> <descripto ...

Developing React component libraries with TypeScript compared to Babel compiler

Currently, I'm utilizing the babel compiler for compiling my React component libraries. The initial choice was influenced by Create React App's use of the same compiler. However, I've encountered challenges with using babel for creating libr ...

Best practices for initializing model objects in a Redux or NgRx application architecture

Context: The development team is currently working on a sophisticated REST-based web application using Angular and the @ngrx library for managing state effectively. In order to represent entities retrieved from the server, such as accounts and users, we ...

What is the best way to overload a function based on the shape of the argument object in

If I am looking to verify the length of a string in two different ways (either fixed or within a specific range), I can do so using the following examples: /* Fixed check */ check('abc', {length: 1}); // false check('abc', {length: 3}) ...

Implementing type inference for response.locals in Express with TypeScript

I need to define types for my response.locals in order to add data to the request-response cycle. This is what I attempted: // ./types/express/index.d.ts declare global { declare namespace Express { interface Response { locals: { ...

What is the process for modifying href generation in UI-Router for Angular 2?

I am currently working on implementing subdomain support for UI-Router. Consider the following routes with a custom attribute 'domain': { name: 'mainhome', url: '/', domain: 'example.com', component: 'MainSiteC ...

Creating a TypeScript client using NSwag with named properties: A step-by-step guide

Our TypeScript client is created from a swagger interface using NSwag. The resulting client code typically looks like this: client.EndPointFoo(arg1, arg2, arg3, ...) However, we encounter issues when NSwag changes the order of arguments in response to mo ...

Show a notification pop-up when a observable encounters an error in an IONIC 3 app connected to an ASP.NET

Currently, I am in the process of developing an IONIC 3 application that consumes Asp.NET web API services. For authentication purposes, I have implemented Token based auth. When a user enters valid credentials, they receive a token which is then stored in ...

Displaying JSON Object in Kendo UI Grid with Incorrect Format

I encountered an issue where a function that I passed to a Kendo Grid field in the fetch method returns perfectly on console.log, but only [object Object] is returned in the Kendo Grid display. Here's the background: I am utilizing two services - Rev ...