What is the reason for Typescript not throwing an error when arguments are missing?

Here is my code snippet:

type Callback = (a: string, b: string) => void

const observer: Callback = function(a: string): void {
  console.log(a)
}

observer('foo')

I am encountering an issue with Typescript on the last line:

Expected 2 arguments, but got 1.(2554)

I wonder why Typescript only raises an error on the observer call instead of detecting it on line 3 where the observer function is defined?

You can test it here: Test Your Code

Answer №1

They provide information in their documentation regarding this topic https://www.typescriptlang.org/docs/handbook/type-compatibility.html#comparing-two-functions

In essence, the reason for this behavior is that in JavaScript it is permissible and somewhat common to disregard extra function parameters. For instance, the code below declares a parameter b, but never utilizes it:

const observer: Callback = function(a: string, b: string): void {
  console.log(a);
}

You might agree that this should comply with the Callback type definition. However, what role does b: string play in the argument list? It only impacts the value of observer.length and the return value of observer.toString(). In practical terms, it often serves as redundant typing.

An example of this concept can be observed with higher-order functions like .map, .filter, .reduce on arrays. These functions accept another function as an argument to define behavior. Despite receiving multiple parameters, you may only require one in many scenarios. Therefore, the following scenario should not generate a type error:

const numbers = [1, 2, 3];
const biggerNumbers = numbers.map(value => value + 1);

Even though your function receives a value, index, and array, it is acceptable to ignore the last two (or even all three, although less common).


In summary: The type definition enforces passing specific values into the function, rather than ensuring that the function actually utilizes those values.

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

Injecting HTML in an Angular Application

I need to modify this code for html injection in an Angular app to ensure it doesn't load any css or animations. dataService.getThings().subscribe( (data) => { const list = document.getElementById("nav-list"); data.forEach((element: a ...

Loop through every item in Typescript

I am currently working with the following data structure: product: { id: "id1", title: "ProductName 1", additionalDetails: { o1: { id: "pp1", label: "Text", content: [{ id: "ppp1", label: "Tetetet" ...

Using Typescript to pass the setState function as a parameter

Consider the scenario below: // external file export const specificFunction = setState => { setState({ value: "some new string" }) } // component's file import { specificFunction } from "pathToFile" interface TState { ...

Obtaining a Bearer token in Angular 2 using a Web

I am currently working on asp.net web api and I am looking for a way to authenticate users using a bearer token. On my login page, I submit the user information and then call my communication service function: submitLogin():void{ this.user = this.l ...

I'm confused why this particular method within a class is not being inherited by the next class. Rather than seeing the expected extension, I am presented with - [Function (

Working fine with the Person class, the register() function displays the correct return statement when logged in the console. However, upon extending it to the Employee class, instead of the expected return statement, the console logs show [Function (anon ...

Error suddenly appeared when trying to serve a previously functional project locally: Firebase function module not found

After not making any changes to my firebase-related files, I suddenly started encountering the following issue that I just can't seem to figure out: We were unable to load your functions code. (see above) - It appears your code is written in Types ...

The implementation is throwing a value type mismatch error. How can I resolve this issue?

enum A { AA = 'AA', BB = 'BB' } export interface OptionsA {a: number} export interface OptionsB {b: string} export interface ValuesA {a: boolean} export interface ValuesB {b: boolean | null} export interface FirstMapA { [ ...

Error: JSON unexpected token ' at position 2 - Solution for fixing this issue

Encountering a recurring JSON error where the user input from a textbox is being passed in JSON for assigning class level permissions in a parse server. var cc = "role:" + user; var jsonParam = "{ 'classLevelPermissions' : { ...

Receiving real-time updates from an Angular 2 service

Having an issue with displaying user nicknames in Angular 2 using the User ID. When attempting to call the getUserName(userId) function from dashboard.component.html, which then triggers the auth0 service to retrieve the user profile, I am encountering con ...

Having trouble getting Chutzpah to work with TypeScript references

I am currently working on a project where my project folder contains the following files: chai.d.ts chai.js mocha.d.ts mocha.js appTest.ts appTest.js chutzpah.json The chai and mocha files were acquired through bower and tsd. Let's take a look at ...

Placing options and a clickable element within a collapsible navigation bar

Within my angular project, there are 4 input fields where users need to enter information, along with a button labeled Set All which will populate them. https://i.sstatic.net/1GGh1.png I am wondering how I can organize these input fields and the button i ...

Configuring Typescript for src and test directories

My TypeScript projects have a structure where the source code is separated from the tests into different directories (src and test). When packaging the final product, I only want to include the source code without the tests because the runtime doesn't ...

How can I choose all the items within an Array that fall within a specific DateTime range?

In order to explore the various methods of querying an array table similar to how MySQL works, I have devised this example. Among the 8 queries presented below, the one that is challenging me is Query (6), which involves using Array.find() in a MySQL Date ...

Encountering a TypeScript error in Next.js: The 'Options' type does not align with the 'NavigateOptions' type

My code snippet: import { useRouter } from 'next/navigation'; interface Options { scroll: boolean; } const Component = () => { const router = useRouter(); const updateSearchParams = () => { const searchParams = new URLSearchPa ...

Angular 8: ISSUE TypeError: Unable to access the 'invalid' property of an undefined variable

Can someone please explain the meaning of this error message? I'm new to Angular and currently using Angular 8. This error is appearing on my console. ERROR TypeError: Cannot read property 'invalid' of undefined at Object.eval [as updat ...

Using data retrieved from a JSON response to make HTTP requests in a recursive manner

I am in the process of extracting all names from an API that provides a JSON response structured like this: { "data" : [ { "attributes" : { "name" : "Prog1" ... ...

In TypeScript, the error "Property does not exist on type 'any[]'" indicates that a specific property is not recognized on

Working on my project using Textscript in Next Js has been mostly smooth sailing, but I keep encountering warnings in my script that say 'Property does not exist on type any[ ]'. The red line under the name, image, and price properties is a sourc ...

What are some techniques for streamlining this code with Typescript?

I am currently working with the following code snippet: let doNavigate = this.currentScreen === removedFqn; if (doNavigate) { location.reload(); } Does anyone have any suggestions on how I can simplify this code using Typescript? ...

The SonarTsPlugin report is coming back clean with no issues found in the Typescript files

In my current project, I am attempting to analyze an Angular application using SonarQube. This particular project consists of a mix of JavaScript and TypeScript files. During the Sonar analysis process, I have noticed that while issues are being generated ...

Unexpected ngStyle behavior: failing to update when property changes occur

I'm feeling a little puzzled about why the ngStyle directive is not behaving as anticipated. I came across this issue while following a tutorial by Brad Traversy on Udemy, where we were instructed to utilize ngStyle in the following manner: <h3 [n ...