Skip to content Skip to sidebar Skip to footer

Typescript: Why Function Without Parameters Can Be Cast To Function With Parameters

Why there aren't any compilation errors in this code? Code: function partial(f: (a: string) => string, a: string) : string { return ''; } var test = () => ''; var result =

Solution 1:

there is an obvious type missmatch and it can possible be a developer's error.

There's nothing obviously wrong with this code. Consider something like this:

let items = [1, 2, 3];
// Print each item in the array
items.forEach(item =>console.log(item));

Is this code correct? Definitely! But forEach invokes its provided function with three arguments, not one. It would be tedious to have to write:

items.forEach((item, unused1, unused2) =>console.log(item));

Note that you can still get errors if you try to do something that's actually wrong. For example:

functionprintNumber(x: number) { console.log(x); }
let strings = ['hello', 'world'];
strings.forEach(printNumber); // Error, can't convert string to number

Post a Comment for "Typescript: Why Function Without Parameters Can Be Cast To Function With Parameters"