Typescript: Implementing a generic function with the flexibility of an optional parameter

Having some difficulty writing a generic function with an optional parameter

type Action<TParameters = undefined> = (parameters: TParameters) => void

const A: Action = () => console.log('Hi :)') 
// This works as expected

const B: Action<string> = (word: string) => console.log('Hello', word)  
// Works as expected

const C: Action<string> = (word: number) => console.log('Hello', word)  
// Error, which is expected

const D: Action<string> = () => console.log('Hello')  
// Unexpectedly no error here

const E: Action<string> = (word) => console.log('Hello', word)  
// No error as anticipated, but the type inference for `word` is `any`, why?

Try it out yourself

Answer №1

One of the main reasons why D passes type checking is due to the common occurrence of ignoring extra parameters in JavaScript. In terms of function parameters, a function f is considered a subtype of another function g as long as each parameter in f is compatible with its corresponding parameter in g. Any additional arguments in f are simply disregarded. For more information on comparing functions, refer to 'Comparing two functions' at here.

(It is worth noting that, as highlighted by @david-sherret, E behaves as expected with word: string.)

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

What limitations prevent me from utilizing a switch statement to refine class types in Typescript?

Unique Playground Link with Comments This is a standard illustration of type narrowing through the use of interfaces. // Defining 2 types of entities enum EntityType { ANIMAL = 'ANIMAL', PLANT = 'PLANT', } // The interface for ani ...

Unusual Behavior of Observable.concat() in Angular 4 with RxJS 5

My Angular 4 / TypeScript 2.3 service has a method called build() that throws an error if a certain property is not initialized. I am attempting to create a safer alternative called safeBuild() that will return an Observable and wait for the property to be ...

Issue with mssql.connect await causing timeout in Jest

Testing some functionality in a nextjs Typescript project that needs to interact with the database directly, not relying on mocked sql query results. But encountering issues with it actually writing to the database. A brief example of the problem: /* @/li ...

The @output decorator in Angular5 enables communication between child and

Hello fellow learners, I am currently diving into the world of Angular and recently stumbled upon the @output decorators in angular. Despite my best efforts to research the topic, I find myself struggling to fully grasp this concept. Here's a snippet ...

Ensuring TypeScript recognizes a class property as definitively initialized when set using a Promise constructor

I have a simple class definition that is giving me an error in TypeScript. class Container { resolveData: (s: string) => void // not definitely initialized error! data: Promise<string> constructor() { this.data = new Promise&l ...

I am experiencing an issue with my date filter where it does not display any results when I choose the same date for the start and end dates. Can anyone help me troub

Having an issue with my custom filter pipe in Angular. When I select the same dates in the start and end date, it doesn't display the result even though the record exists for that date. I've noticed that I have to enter a date 1 day before or ea ...

What is the process for utilizing ts-node ESM in conjunction with node modules?

Disclaimer: I understand that the question below pertains to an experimental feature. I have initiated a thread on the ts-node discussion forum. Nonetheless, I believe that posting on StackOverflow will garner more visibility and potentially result in a qu ...

Autocomplete feature shows usernames while storing corresponding user IDs

I am looking to enhance the autocomplete functionality in my application while also ensuring that the selected user ID is stored in the database. Specifically, I want the autocomplete feature to display user names for selection purposes, but instead of re ...

Having trouble with VS Code on my Linux system - npm error popping up?

protons@protons-HP-EliteBook-840-G3:~/Desktop/NH_Facility_Portal_V0$ sudo npm install [sudo] password for protons: npm notice npm notice New minor version of npm available! 8.12.1 -> 8.13.2 npm notice Changelog: https://github.com/npm/cli/releases/tag ...

Learning to implement forwardRef in MenuItem from Material-UI

Encountering an error when pressing Select due to returning MenuItem in Array.map. Code const MenuItems: React.FC<{ items: number[] }> = (props) => { const { items } = props; return ( <> {items.map((i) => { return ( ...

Can classes be encapsulated within a NgModule in Angular 2/4?

Looking to organize my classes by creating a module where I can easily import them like a separate package. Take a look at this example: human.ts (my class file) export class Human { private numOfLegs: Number; constructor() { this.numOfLegs = 2 ...

Utilizing various settings using `.env` files in NodeJs

As I work on building a backend in nodejs, one of the key considerations is how to incorporate an environment configuration into the project. I am envisioning a structure where there is a /config folder housing my envparser.ts (still brainstorming a catchi ...

The correlation between the node.js version and the @types/node version

I recently started exploring node.js and decided to experiment with using TypeScript alongside it. After running npm install @types/node, I found that the latest version available was 7.0.4: $ npm install @types/node <a href="/cdn-cgi/l/email-protectio ...

Bringing in a service from a different module in NestJS

Having an issue trying to utilize the surveyService within the voteOptionRepository. When attempting to use the route, the console displays: TypeError: this.surveyService.getSurveyById is not a function Below is my SurveyModule setup: @Module({ im ...

Tips for guaranteeing the shortest possible period of operation

I am in the process of constructing a dynamic Angular Material mat-tree using data that is generated dynamically (similar to the example provided here). Once a user expands a node, a progress bar appears while the list of child nodes is fetched from the ...

Tips on properly declaring props in Typescript when a parent component is passing props down to its children componentsуж

When a parent component clones its children to pass props to them, how can we specify the type of props for the children? I'm encountering an issue because injectedProps is expected in the Child component const Parent: React.SFC<ParentProps> = ...

What steps can I take to guarantee that the observer receives the latest value immediately upon subscribing?

In my Angular 2 and Typescript project, I am utilizing rxjs. The goal is to share a common web-resource (referred to as a "project" in the app) among multiple components. To achieve this, I implemented a service that provides an observable to be shared by ...

When calling UIComponent.getRouterFor, a TypeScript error is displayed indicating the unsafe return of a value typed as 'any'

I have recently integrated TypeScript into my SAPUI5 project and am encountering issues with the ESLint messages related to types. Consider this simple example: In this snippet of code, I am getting an error message saying "Unsafe return of an any typed ...

Could this type declaration in the Vue decorator constructor be accurate?

When using Vue decorator notation, I typically write it like this: @Prop({ type: Object || null, default: null }) However, I noticed in the Vue documentation that they use array notation: @Prop({ type: [ Object, null ], default: null }) Is there a specif ...

Creating a personalized event using typescript

I need help with properly defining the schema for an EventObject, specifically what should be included within the "extendedProps" key. Currently, my schema looks like this: interface ICustomExtendedProps { privateNote?: string; publicNote?: string; ...