1

It seems that function with no args (like ()=>any) is OK for any function type.

For example:

function foo(bar: number): void;
function foo():void {} //no type errors here!

or this:

let t: (a: number) => void;
t = ()=> {};

Why TypeScript doesn't complain about different types in these cases? Is this a feature, some kind of shortcut?

0

2 Answers 2

2

It's a feature. The type definitions for functions are there to make it mandatory that certain values be passed in. It does not make it mandatory that the function actually do something with it.

This is done because it's actually pretty common in javascript to ignore some of the things you were passed in. For example, consider this array.map usage:

const smallNumbers = [1, 2, 3];
const bigNumbers = smallNumbers.map((value: number) => value * 10);

I've passed in a mapping function that takes in a number and returns another number. This code should be treated as ok, since it's a standard way to use map, but map will actually pass 3 arguments into my function, not just one. It would be a pain if i had to explicitly write those extra parameters, even though i have no intention of using them:

const bigNumbers = smallNumbers.map((value: number, index: number, array: number[]) => value * 10);

You can read more about this here

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. But what if I want to strictly specify number of args. Is there a way to do it?
Not that i'm aware of.
1

In JavaScript, you can use a function which takes fewer arguments than are passed. For example:

document.querySelector('#my-button').addEventListener('click', () => console.log('clicked');

You could have also had the callback look like (event) => console.log('clicked').

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.