type FuncWith2ParamAndReturnVoid = (a: number, b: string) => void;
let func: FuncWith2ParamAndReturnVoid = function (): number {
return 0;
} // ??? where error?
It is assignable indeed.
void means there is no return value, so that whatever value you want to return, that does not matter, since no one uses its return value.
If you want to force check its return type, use void as function return type instead.
type FuncWith2ParamAndReturnVoid = (a: number, b: string) => void;
let func: FuncWith2ParamAndReturnVoid = function (): void {
// ^^^^
return 0;
// ^^^^^^^^ [ts] Type '0' is not assignable to type 'void'.
}
@ikatyang why the parameters are not taken into account?
for example:
function forEach(array: any[], callback: (value: any, index: number, array: any[]) => void) {
for (let i = 0; i < array.length; i++) {
callback(array[i], i, array);
}
}
// the following cases are all assignable
forEach([1, 2, 3], (n, i, a) => console.log(n, i, a));
forEach([1, 2, 3], (n, i) => console.log(n, i));
forEach([1, 2, 3], n => console.log(n));
// ^
// you can omit its parameter
@ikatyang problem as an example?? This is nonsense. Must be
(value?: any, index?: number, array?: any[]) => void
and so, it's another bug.
@olegdunkan the name of the topic on the link
Why are functions with fewer parameters assignable to functions that take more parameters?
I understand. But in my case Vice versa!
FuncWith2ParamAndReturnVoid has two parameters, function (): void { return 0; } has zero parameters,
you assign function (): void { return 0; } to FuncWith2ParamAndReturnVoid
I understand that this is expected behavior.I understand that it is even documented.But the truth is that it came up with a crazy person!It should be congratulated!He invented a new form of typing - jelly typing!
Why the objects are compared structurally less = more. And functions - more = less?
Typescript is the very wise language it combines dynamic nature and experience of java script programming and type-safe languages like C#, C++.
@olegdunkan is not noticeable. I spent two years of his praise, and now I think that this is another ms product.
@acopalipsis Please stop using the issue tracker as a support forum or discussion board. This is not the correct place to ask questions, complain about FAQ answers, or :-1: people who are responding to your questions. You are free to disagree with design decisions made in TypeScript but the issue tracker is for tracking bugs, and we do not consider these behaviors to be bugs.
Most helpful comment
See spec
See FAQ