Utilizing default signatures for function overloading

In my code, there is a function called myFunction that takes in two parameters:

  • key which can be either "mode", "foo", or "bar"
  • value of type any. However, if the key is "mode", then the value must be of type Mode

I attempted to implement function overloading for this, but unfortunately, it did not work as intended. My goal was to have one signature specifically for when key is equal to "mode", and another "catch-all" signature for all other cases.

export const KEYS = Object.freeze({   
  mode: "mode",
  foo: "foo",
  bar: "bar",
});
export type Key = (typeof KEYS)[keyof typeof KEYS];

export const MODES = Object.freeze({
  TABLE: "table",
  CARDS: "cards",
});
export type Mode = (typeof MODES)[keyof typeof MODES];

function myFunction(
  key: "mode",
  value: Mode
): void;
function myFunction(key: Key, value: any): void {
    console.log(key, value)
}

myFunction("mode", "cards"); // OK
myFunction("foo", 123); // Argument of type '"foo"' is not assignable to parameter of type '"mode"'.
myFunction("bar", "test"); // Argument of type '"bar"' is not assignable to parameter of type '"mode"'.

Playground

Why isn't my implementation working as expected? Should I provide more explicit signatures for each case?

Answer №1

After some clarification from @jcalz, I now understand that I had mixed up overload signatures with the implementation signature. For more information, you can check the documentation.

To resolve this confusion, I defined the desired "fallback" signature separately from the implementation signature. You can test it out in the Playground

export const KEYS = Object.freeze({
  mode: "mode",
  foo: "foo",
  bar: "bar",
});
export type Key = (typeof KEYS)[keyof typeof KEYS];

export const MODES = Object.freeze({
  TABLE: "table",
  CARDS: "cards",
});
export type Mode = (typeof MODES)[keyof typeof MODES];

// call signatures
function myFunction(key: "mode", value: Mode): void;
function myFunction(key: Exclude<Key, "mode">, value: any): void; // Note Exclude<>

// impl
function myFunction(key: Key, value: any): void {
  console.log(key, value)
}

myFunction("mode", "cards"); // OK
myFunction("mode", "should fail"); // 👍 No overload matches this call.
myFunction("foo", 123); // OK
myFunction("bar", "test"); // OK

Note

Exclude<Key, "mode">
. Without it
myFunction("mode", "should fail")
will not throw an error.

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

When the boolean in RxJS skipWhile remains true

My current scenario involves a specific use-case: There is a service that queues calculation tasks assigned with a certain ID. I have set up an observable to monitor the status of the service. When the ID is still in the queue, the query result is true (i ...

Derived a key from an enum member to be used as an interface key

I am attempting to configure an object property by selecting its key using a computed key, via an enum, as shown in the code snippet below. Unfortunately, solutions 1 and 2 are not functioning. These are the solutions I need to implement in my code becaus ...

How can I retrieve List<T> from a Razor Page using TypeScript?

Within my ViewModel, I have an Items collection: public class ItemViewModel{ public List<Item> Items {get;set;} } In the Index.cshtml file: @if(Model.Items != null){ <li><a id="item-id-link" href="#" data-items="@Model.Items"> ...

Bring in Event Types from React using TypeScript

Is there a way to import Event Types from React and use them in Material-ui? Specifically, I am looking for guidance on how to import KeyboardEvent so that it can be utilized for onKeyDown callback type annotation. I have examined the .d.ts file of Mater ...

What is the process for connecting custom transformers to a compiler host?

My custom TypeScript watcher is set up like this: const compilerHost = typescript.createWatchCompilerHost(config.fileNames, config.options, typescript.sys, undefined, reportDiagnostic) typescript.createWatchProgram(compilerHost) I am trying to integrate ...

Enhancing the getDate function in JavaScript with additional days

My function for selecting the date is working perfectly: formatDateField(event: Date, formControl: string) { this.form .get(formControl) .patchValue( this.datePipe.transform(event.getTime(), "yyyy-MM-dd'T'HH:mm:ss&quo ...

What is the specific category of Mongoose.startSession in the realm of Typescript?

In my Express/Typescript project with mongoose, I implemented a loader as follows: import mongoose from 'mongoose'; import { Db } from 'mongodb'; import config from '../config'; export default async (): Pr ...

Implementing a video pause event trigger from a function in Angular2

Here is the content of my player.component.html: <video width="320" height="240" autoplay autobuffer [src]="videoSrc" (ended)="videoEnd()"> Your browser does not support the video tag. </video> <button (click)="pauseOrPlay()">pause/play ...

Tips for selecting specific regions on an Angular SVG map

For my Angular TypeScript project, I included a map. Does anyone know how to create a select region on the map? Click here for StackBlitz Here is the jsFiddle code link CSS styles here p { font-size: 12px; } #core { fill: #ff4f81; animatio ...

Exploring the concept of rest arrays within a destructured object

Is there a way to declare c as an optional array of any type in this code snippet? const a = ({ b, ...c }: { b: string, c: ? }) => null ...

Automatically closing the AppDateTimePicker modal in Vuexy theme after selecting a date

I am currently developing a Vue.js application using the Vuexy theme. One issue I have encountered is with a datetimepicker within a modal. The problem arises when I try to select a date on the datetimepicker component - it closes the modal instead of stay ...

The Azure GraphQL serverless function encountering an issue with the Cosmos DB connection, displaying an

After developing a serverless GraphQL API function using Azure functions and connecting it to Cosmos DB, I have encountered an issue with "Invalid URL" that has been puzzling me for a week. Despite running the graphql function locally without any problems, ...

Locate a specific element within a multi-dimensional array based on a partial match of one of its properties with a provided text

I am working with an array that includes three properties: ID : number Name : string Description :string ItemList :array<T>=[] and ItemListCopy :array<T>=[] Currently, this array is linked to the ng-multiselect dropdown During the onFilt ...

What's wrong with the current longitude and latitude bounding box algorithm used for geolocation searches?

I am currently working on a piece of code that calculates a bounding box for a specific location to search for user profiles within a given radius. The code is mostly functional, but I am encountering a slight distortion in the final values. When I input 5 ...

The upload cannot be completed as the file upload is not in a multipart request format

This file upload code was referenced from this source. The issue lies in the fact that it is sending the request as JSON instead of multipart form data, causing the server side code to reject the request and resulting in a failed upload. I have confirmed ...

typescript locate within the union type in the mapping expression

Consider the following: type X = { label: 'Xlabel', X_id: 12 }; type Y = { label: 'Ylabel', Y_id: 24 }; type Z = { label: 'Zlabel', Z_id: 36 }; type CharSet = X | Y | Z; I am looking for type CharSetByLabel = Map<CharSet& ...

Getting News API and showcasing the information in Vuetify.js card components: A step-by-step guide

I'm trying to develop a news website by utilizing the News API for news data. I obtained an API Key from the official News API website, but my code is encountering some issues. The error message reads: TypeError: response.data.map is not a function ...

The Gulp task is stuck in an endless cycle

I've set up a gulp task to copy all HTML files from a source folder to a destination folder. HTML Gulp Task var gulp = require('gulp'); module.exports = function() { return gulp.src('./client2/angularts/**/*.html') .pipe( ...

When merging interfaces and classes, Typescript does not verify property initialization

When creating a class like the following: class Dog { a: string; b: string; c: string; } The TypeScript compiler will throw an error stating that properties a, b, and c are not initialized. However, if we take a different approach like this: i ...

Issue encountered with Typescript and Request-Promise: Attempting to call a type that does not have a call signature available

I have a server endpoint where I want to handle the result of an asynchronous request or a promise rejection by using Promise.reject('error message'). However, when I include Promise.reject in the function instead of just returning the async requ ...