TypeScript disregards interface method argument types

Unexpectedly, the code below compiles without any errors (using tsc 3.9.5):

interface IDateHandler {
  handleDate: (Date) => void;
}

let dateHandler: IDateHandler = {
  handleDate: (d: Date) => {},
};

dateHandler.handleDate([1, 2, 3]);

Even more surprising is that if handleDate([1, 2, 3]) is replaced with handleDate([1, 2, 3], 4), tsc throws

error TS2554: Expected 1 arguments, but got 2.

Clearly, it recognizes the function signature of handleDate, yet it seems to be disregarding the actual types.

Even more surprisingly, removing the interface declaration causes type checking to work correctly:

let dateHandler = {
  handleDate: (d: Date) => {},
};

dateHandler.handleDate([1, 2, 3]);

// error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'Date'.
//   Type 'number[]' is missing the following properties from type 'Date': toDateString, toTimeString, toLocaleDateString, toLocaleTimeString, and 37 more.

What's happening here?

Answer №1

Upon viewing the code, my immediate observation is that there appears to be an issue on line 2. The handleDate signature should include a specified param type.

Despite this potential error, the code manages to compile because it is technically valid. Within the code, there exists a param labeled Date with no designated type.

To rectify this situation, it is advisable to incorporate either the --strict or --noImplicitAny compiler options into your tsc configuration (whether in tsconfig.json or via command line parameters). This adjustment should prompt an error similar to:

Error:(2, 18) TS7051: Parameter has a name but no type. Did you mean 'arg0: Date'?

For further information, refer to: Typescript Compiler Options

Answer №2

After seeing @VLAZ's comment, I was able to figure out the issue on my own:

When TypeScript's default setting for "implicit any" is activated, (Date) => void transforms into (Date: any) => void.

By adjusting the function type definition to (d: Date) => void, the tsc compiler correctly shows the error message as anticipated:

error TS2345: Argument of type 'number[]' is not assignable to parameter of type 'Date'.

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 is the best way to change multiple parameters using ngModelChange?

I have a requirement in my application to update 3 values using a single ngModelChange event. The component structure is as follows: model: any = {}; images: any; public input = true; public dropdown = false; images : any; constructor(...services) { } ...

AgGrid Encounters Difficulty in Recovering Original Grid Information

After making an initial API call, I populate the grid with data. One of the fields that is editable is the Price cell. If I edit a Price cell and then click the Restore button, the original dataset is restored. However, if I edit a Price cell again, the ...

Guide to Dynamically Including an Element in an Array using Typescript

Encountering a type error within the <RenderFormFields formFields={formFieldsData} /> component:- Types of property 'type' are not compatible. Type 'string' cannot be assigned to type '"select"'.ts(2322) Rende ...

How can I only accept one of two specific function signatures in Typescript and reject any others?

Looking for an answer from the community on Typescript, require either of two function signatures In my code, I am handling a callback where I need to either pass an error or leave the first argument as undefined and pass data as the second argument. To ...

Changing a method within a class does not automatically update how it is used in other classes that inherit from it

I am attempting to modify the alpha method in the context of the Cat class, and have the beta method reflect those modifications. const wrapperFn = <T extends (...args: any) => any> (a: T) => { return (...args: Parameters<T>) => ...

The cursor in the Monaco editor from @monaco-editor/react is not aligning with the correct position

One issue I am facing with my Monaco editor is that the cursor is always placed before the current character rather than after it. For example, when typing a word like "policy", the cursor should be placed after the last character "y" but instead, it&apos ...

Refreshing Form in Angular 2

When I remove a form control from my form, it causes the form to always be invalid. However, if I delete a character from another input field and then add the same character back in (to trigger a change event), the form becomes valid as expected. Is ther ...

Is there a method to restrict the scope of identical components appearing multiple times on a single page in Angular 7?

I have a scenario where I need to place multiple instances of the same component on a page, but when one of them receives input and refreshes, all other components also refresh. Is there a way to prevent this from happening? <tr *ngFor="let map of imgs ...

Inheritance of Type Member in TypeScript

My data structure looks like this: export abstract class Person { ... } export class FPerson extends Person { a: A; b: B; } export class JPerson extends Person { c: C; } export class User { person: Person; } When dealing with the s ...

Tips for resolving the AWS CDK setContext error while updating beyond v1.9.0

Attempting to upgrade AWS CDK code from version 1.9.0 to version 1.152.0, I encountered a problem with the setContext code no longer being valid. The error message states ‘Cannot set context after children have been added: Tree’ The original code tha ...

There are no HTTP methods available in the specified file path. Make sure to export a distinct named export for each HTTP method

Every time I attempt to run any code, I encounter the following error message: No HTTP methods exported in 'file path'. Export a named export for each HTTP method. Below is the content of my route.ts file: import type { NextApiRequest, NextApi ...

Tips for refining search criteria with a combination of checkbox and range slider in Angular 2

In an attempt to refine the results for the array "db," I have implemented three filters: price, duration, and category. I have experimented with using the filter() method to apply these filters. You can find the code I have worked on here: https://stack ...

Error in Typescript TS2322: Observable Type 'boolean | {}' - Using Angular 5 and Typescript 2.4.2

After upgrading from version 4 to 5, I'm puzzled by the plethora of TypeScript TS2322 errors I'm encountering. The migration involved setting up a new Angular project with the Angular CLI. Angular CLI: 1.5.5 Node: 8.9.1 OS: darwin x64 Angular: 5 ...

Building stateless functional components in React using Typescript version 0.14

Demonstration: import * as React from 'react' declare function obtainMarineLife(x: any): any; declare var Tank: any; var OceanicHabitat = ({category}) => ( <Tank> {obtainMarineLife(category)} </Tank> ); let y = <Ocea ...

Streamline imports with Typescript

Is there a way to import modules with an alias? For example, I have an angular service in the folder common/services/logger/logger.ts. How can I make the import look like import {Logger} from "services" where "services" contains all my services? I've ...

What is the proper way to utilize the ES6 import feature when using a symbolic path to reference the source file?

I am seeking a deeper understanding of the ES6 import function and could use some assistance. The Situation Imagine that I have a portion of code in my application that is frequently used, so I organize all of it into a folder for convenience. Now, in t ...

Troubleshooting a TypeScript error when trying to access an imported service in Angular 2

I've been working on creating a form that allows users to input required details, which will trigger a server call and save the information. However, no matter what I try, I keep encountering the following error: ORIGINAL EXCEPTION: TypeError: this.po ...

Having trouble resolving parameters? Facing an Angular dependency injection problem while exporting shared services?

Seeking to streamline the process of importing services into Angular 4 components, I devised a solution like this: import * as UtilityService from '../../services/utility.service'; As opposed to individually importing each service like so: imp ...

Inference in Typescript - Detecting unknown key in an object

I am struggling to implement type inference from a props object that is passed to a component and then used in a render function. While I can retrieve the keys of the object correctly, all types are being interpreted as unknown. I need some assistance in f ...

Implementing advanced error handling using custom error messages with enums

I'm trying to use Zod to validate a gender field with z.nativeEnum(), but for some reason my custom error messages are not being applied: gender: z.nativeEnum(Gender, { invalid_type_error: 'Le sexe doit être homme ou femme.', ...