Back to questions
JuniorTheoryCommon
What happens when this program is compiled and run (lines separated by spaces)?
type Handler = (value: number, index: number) => void;
function each(nums: number[], fn: Handler) {
for (let i = 0; i < nums.length; i++) {
fn(nums[i], i);
}
}
each([1, 2], (v) => console.log(v));tsc is silent, and the program prints 1 2
- Expecting an error about the missing
index: a function with fewer parameters fits a function type with more, because it may leave the extra arguments unread. - Expecting
vto be implicitlyany: an arrow passed where aHandleris expected takes its parameter types fromHandler.
- What does tsc report if the callback is
(v, i, extra) => console.log(v)? - Why does TypeScript allow a callback with fewer parameters but not one with more?