Can Typescript automatically determine the return type based on the function argument value?

How can Typescript be utilized to deduce the return type from the valueType parameter instead of using overloads?

 type ValueType = 'integer' | 'string' | 'number' | 'date' | 'dateTime' | 'boolean' | '';

   function toValueType<S>(v: S, valueType: 'integer'): number;
   function toValueType<S>(v: S, valueType: 'number'): number;
   function toValueType<S>(v: S, valueType: 'date'): Date | undefined;
   function toValueType<S>(v: S, valueType: 'dateTime'): Date | undefined;
   function toValueType<S>(v: S, valueType: 'string'): string;
   function toValueType<S>(v: S, valueType: ''): S;
   function toValueType<S>(v: S, valueType: ValueType): any {
        switch (valueType) {
            case 'integer':
                return To.int(v); // returns number
            case 'number':
                return To.number(v); // returns number
            case 'date':
                return To.date(v); // returns Date|undefined
            case 'dateTime':
                return To.dateTime(v); // returns Date|undefined
            case 'string':
                return To.string(v); // returns string
            case 'boolean':
                return To.boolean(v); // returns boolean
            default:
                return v; // returns source
        }
    } 

Answer №1

You have the option to define a type alias that maps each string literal in your ValueType union to its expected return type. Additionally, you can introduce a separate generic type parameter for selecting the correct type within a conditional return type scenario:

Try experimenting with this in the TS Playground

type ValueMap = {
  boolean: boolean;
  date: Date | undefined;
  dateTime: Date | undefined;
  integer: number;
  number: number;
  string: string;
};

type ValueType = keyof ValueMap | "";

declare function toValueType<T, K extends ValueType>(
  v: T,
  valueType: K,
): K extends keyof ValueMap ? ValueMap[K] : T;

declare const v: { _type: "example" };

const r0 = toValueType(v, "boolean");
    //^? const r0: boolean

const r1 = toValueType(v, "date");
    //^? const r1: Date | undefined

const r2 = toValueType(v, "dateTime");
    //^? const r2: Date | undefined

const r3 = toValueType(v, "integer");
    //^? const r3: number

const r4 = toValueType(v, "number");
    //^? const r4: number

const r5 = toValueType(v, "string");
    //^? const r5: string

const r6 = toValueType(v, "");
    //^? const r6: { _type: "example"; }

toValueType(v, "something else"); /* Error
               ~~~~~~~~~~~~~~~~
Argument of type '"something else"' is not assignable to parameter of type 'ValueType'.(2345) */

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

Tips on informing the TS compiler that the value returned by a custom function is not null

There might be a way to make this code work in TypeScript, even though it's currently showing some errors regarding possible undefined values. Take a look at the code snippet: const someArray: foo[] | null | undefined = [...] // TS fail: someArray ...

Angular 4: Conditional CSS classes causing issues with transitions

After scouring through stackoverflow, I have yet to find a solution to my current issue. I am utilizing a conditional class on a div that is applied when a boolean variable becomes true. Below is the code snippet in question: <div [class.modalwindow-sh ...

What is a quick way to assign object properties to another object in TypeScript?

Sample: response.rooms.push({ maxPlayers: doc.maxPlayers, ownderId: doc.ownderId, roomId: doc.ownderId, state: doc.state, type: doc.type, }); All the parameters share the same name here. However, the doc object has additional parameters that I d ...

"Incorporating the node_modules folder into the Express.js compilation process

Is there a way to automatically include dependencies during Express.js compilation, similar to building a React project? I want to avoid dealing with dependencies after the build process. Any suggestions on how to achieve this? I have not attempted any so ...

How can we ensure that material-ui fields render properly following a reset call in react-hook-form?

I am currently working on a page for editing, but I have encountered an issue with react MUI not rendering text fields properly after updating my form data using the reset method from react-hook-form. This is the current appearance of the form: When I cl ...

Implement the click event binding using classes in Angular 2

If I have the template below, how can I use TypeScript to bind a click event by class? My goal is to retrieve attributes of the clicked element. <ul> <li id="1" class="selectModal">First</li> <li id="2" class="selectModal">Seco ...

When attempting to assign a 'string' type to the @Input property, I am receiving an error stating that it is not assignable to the 'PostCard Layout' type

Encountering an issue The error message 'Type 'string' is not assignable to type 'PostCard Layout'' is being displayed A parent component named page-blog.component.html is responsible for defining the class styles and passi ...

Having trouble sending the request body via next-http-proxy-middleware

Recently, I've been attempting to develop a frontend using nextjs that communicates with a Java backend. To achieve this, I'm utilizing the npm package next-http-proxy-middleware. However, it seems like either my request body is getting lost in t ...

Transmitting language codes from Wordpress Polylang to Angular applications

I am currently attempting to manage the language settings of my Angular application within WordPress using WordPress Polylang. To achieve this, I have set up the following structure in my Angular application: getLanguage.php <?php require_once(". ...

Tips for integrating Typescript Definition files with Visual Studio 2017

I have a challenge with my ASP.NET Core 2.0 application where I am attempting to incorporate TypeScript and jQuery. While TypeScript integration has been successful, I am facing issues with jQuery as it does not provide me with intellisense. Despite trying ...

To ensure the next line only runs after the line above has finished executing, remember that the function is invoked in HTML

my.component.html <button (click)="refresh()">Refresh</button> my.component.ts refresh() { let self = this; self.isRefresh = true; //1st time self.getfun().then(() => { self.isRefresh = false; ...

Guide to setting a SetState function within a component (Using NextJS and TypeScript)

I'm currently diving into TypeScript, and I've hit a roadblock when it comes to the correct assignment for my setState function that I need to pass to a component. /index.tsx import { Dispatch, SetStateAction, useState } from "react"; ...

I'm experiencing difficulty in scrolling on my Nextjs web application

Currently, I am facing an issue with my portfolio webpage which is divided into 3 main components - Hero, About, and Portfolio. The layout structure is as follows: export default function RootLayout({ children, }: { children: React.ReactNode }) { ret ...

The absence of the import no longer causes the build to fail

Recently, after an update to the yup dependency in my create react-app project, I noticed that it stopped launching errors for invalid imports. Previously, I would receive the error "module filename has no exported member X" when running react-scripts buil ...

How can you add or remove an item from an array of objects in Angular/RXJS using Observables?

Purpose: The goal is to append a new object to an existing Observable array of objects and ensure that this change is visible on the DOM as the final step. NewObject.ts: export class NewObject { name: string; title: string; } Here's the example ...

Improving the App() function in React and Typescipt

When working on my React/Typescript app, I encountered a challenge with the length of the code in one of the sections. Despite watching tutorials and searching for solutions, I couldn't find a clear way to refactor it. The specific issue is with refa ...

How can I ensure that PrimeNG is functioning properly?

I'm encountering some difficulties setting up PrimeNG correctly to utilize its rich text editor. Despite installing all the necessary components, it's still not functioning as expected. https://i.stack.imgur.com/4kdGf.png This is my package.jso ...

Use a function on values that have corresponding keys in a separate array

I am working with a form.value object that looks like this: form.value = { "to_date": "2019-03-21T05:00:00.000Z", "from_date": "2019-03-13T05:00:00.000Z", "is_form": "" "errors":"" } Additionally, I have an array called filterArray: filterArray ...

Learning how to use arrow functions with the `subscribe` function in

Can someone help clarify the use of arrow functions in TypeScript with an example from Angular 2's Observable subscribe method? Here's my question: I have code that is functional: this.readdataservice.getPost().subscribe( posts =&g ...

Tips for importing a module such as 'MyPersonalLibrary/data'

Currently, I am developing a project with two packages using Typescript and React-Native: The first package, PackageA (which is considered the leaf package), includes a REST client and mocks: MyOwnLibrary - src - tests - mocks - restClientMoc ...