typescript function discrimination

const enum Tag {
  Friday = 'Friday',
  Planning = 'Planing',
}
const test = (tag: Tag, task:/* ??? */): string => {/* some logic */}

If tag is set to Tag.Friday, then the function task should expect a parameter of type (tour: string) => string

If tag is set to Tag.Planning, then the function task should expect a parameter of type (date: Date) => string

I attempted to use function discriminated union and function overloads, but neither was able to infer the type of task. You can check out my code in the TS Playground

Answer №1

If you want to utilize function overloading in TypeScript, you can achieve this by defining your function as an interface.

Here's an example:

const enum Tag {
  Friday = 'Friday',
  Planning = 'Planing',
}
type TourFunc = (tour: string) => string
type DateFunc = (date: Date) => string
interface Fn {
  (tag: Tag.Friday, todo: TourFunc): string;
  (tag: Tag.Planning, todo: DateFunc): string;
}

const test: Fn = (tag: Tag, todo: TourFunc | DateFunc): string => {
  return 'a';
}

const dateFunc : DateFunc = (a: Date) => a.toDateString()
const tourFunc : TourFunc = (b: string) => b
test(Tag.Planning, (s: string) => 'a'); // Error
test(Tag.Planning, dateFunc); // Ok 
test(Tag.Friday, tourFunc); // Ok
test(Tag.Planning, tourFunc); // Error

Try it out on the Playground!

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

The argument labeled as 'State' cannot be assigned to a parameter labeled as 'never'

I've recently delved into using TypeScript with React. I attempted to incorporate it with the React useReducer hook, but I hit a roadblock due to an unusual error. Below is my code snippet: export interface ContractObj { company: string; ...

The React table column definition inexplicably transforms into a string

When working with react-table in Typescript, I encountered an issue while defining the type for my columns within a custom hook. It seems that when importing the hook and passing the columns to my Table component, they are being interpreted as strings inst ...

Retrieving user input from one component to be used in another component in Angular

I'm currently working on a structure that involves a navbar component and a form component https://i.stack.imgur.com/nPRLO.png Initially, I have a navbar component where I load user data using an ID stored in the session. In the right side component ...

What causes an error when the App is enclosed within a Provider component?

What is causing the error when wrapping the App in Provider? Are there any additional changes or additions needed? Error: "could not find react-redux context value; please ensure the component is wrapped in a @Provider@" import React from ' ...

Displaying the content of the subarray

I am attempting to showcase the data stored in the array products from home.ts on the home.html file. export class HomePage { public products: any[] = [ { theater: { '30': { id: '44', name: ' ...

adjust the child component by directly accessing its reference

Struggling to update a child component from the parent component using its reference, but running into some issues. Here's what I've attempted so far: class MainApp extends React.Component<any, any> { construct ...

Incorporate Font Awesome icons throughout your Angular8 application for added visual appeal

I'm currently working on a large Angular application that utilizes lazy loading modules. Throughout various components in different modules, I make use of icons from Font Awesome individually. Here is an example: In component.ts: import { faChevronD ...

Formik button starts off with enabled state at the beginning

My current setup involves using Formik validation to disable a button if the validation schema is not met, specifically for a phone number input where typing alphabets results in the button being disabled. However, I encountered an issue where initially, ...

What steps should I take to resolve an unhandled promise error in a React TypeScript application while making an axios POST request?

I am currently working on a .tsx file to implement adding an enterprise feature. Although I can input data, clicking the submit button does not trigger any action. My application includes a page that has a button for adding a new enterprise. Upon clickin ...

What is the process for generating an array of objects using two separate arrays?

Is there a way to efficiently merge two arrays of varying lengths, with the number of items in each array being dynamically determined? I want to combine these arrays to create finalArray as the output. How can this be achieved? My goal is to append each ...

Making changes to a single formControl in angular6 will cause the other formControl to be updated as

I have two select menus in my user interface with the same options. When I select an option in one menu, I want the other menu to display the same option, and vice versa. Currently, I am using the valueChanges method on the first formControl to update the ...

Generate random entries from an object based on specific criteria and append them to a fresh object using Typescript

Experimenting with Ionic2 and Typescript has been my recent focus. I have an object that contains various meals, calorie counts, and meal types (such as vegan). This is how the object looks: [ { "id":14093, "name":"Proteinshake mit Wasser ...

What is the best way to transfer information from one column to another column with Office Scripts?

I'm in the process of automation with Microsoft Excel using Office Scripts, and I've hit a roadblock when trying to transfer data from one column to another. https://i.sstatic.net/56ipi.png Specifically, I need to move the data from the Date co ...

Distinguishing Between TypeScript Interface Function Properties

Could anyone clarify why the assignment to InterfaceA constant is successful while the assignment to InterfaceB constant results in an error? interface InterfaceA { doSomething (data: object): boolean; } interface InterfaceB { doSomething: (data: obje ...

The POST requests on Next JS Mock API endpoints include parameters passed in the req.body

I am currently running Next JS API tests using jest with a custom testClient. The code for the testClient is as follows: import { createServer } from 'http'; import type { NextApiHandler } from 'next'; import type { __ApiPreviewProps } ...

Check to see if the upcoming birthday falls within the next week

I'm trying to decide whether or not to display a tag for an upcoming birthday using this boolean logic, but I'm a bit confused. const birthDayDate = new Date('1997-09-20'); const now = new Date(); const today = new Date(now.getFullYear( ...

What is preventing me from manipulating this Object outside of the ngOnInit() function?

I've been working on a project that involves fetching data from the server and manipulating it within the .ts file. However, I seem to be facing a common issue related to Typescript/angular concepts that I'm struggling to grasp...I would really a ...

Is there a method in Typescript to constrain an exported function's accessibility so that it is only importable by specific files?

I would like developers to use a class or interface instead of directly importing functions. Is there a way to restrict so only the class can import the function? I prefer not to consolidate all the functions in a single file, especially in a large proje ...

Tips on deleting a nested JSON key?

Here is an example of my JSON structure: var data = [{ "ID" : 3, "discRec" : "Some sample record", "Tasks" : [{ "ID" : 7, ...

Adding TypeScript definition file to an npm package: A step-by-step guide

Is it possible to include typescript definitions (.d.ts files) in a pure javascript project without using TypeScript itself? I'm struggling to find any information on how to do this directly in the package.json. ...