Root Cause: No Type Annotation
While other answers solve the symptom, I don't believe they have addressed the underlying problem in your code, which is here:
var add = function (Num) { return console.log(Num.num1 + Num.num2); };
The parameter here is called Num, and has no type. I believe you intended this to be:
// name: type
const add = function (num: Num) { return console.log(num.num1 + num.num2); };
Calling Add
Your code isn't in a particular context, so let's drop this for a second and look at the call to the add function:
// ERROR: Expected 1 arguments, but got 2.
// const add: (num: Num) => void
add(1, 2);
TypeScript is now helping you to see the error in your call. Solving the call to add without solving your root cause fixed the symptom, but not the underlying issue.
You can now update your call to add with:
add({ num1: 1, num2: 2 });
And it will work - but so will all future calls; because your add function now had type information.
Demo
Drop the following into a TypeScript file, or the TypeScript Playground, to see this in action:
interface Num {
num1: number;
num2: number;
}
const add = function (num: Num) { return console.log(num.num1 + num.num2); };
add(1, 2);
add({ num1: 1, num2: 2 });
add(1, 2)
If you want to have an add method that allows the signature add(1, 2) you need to change the signature... the fully annotated function itself can be described as:
const add = function (a: number, b: number): number {
return a + b
};
If you want to see what the interface looks like for this, it is below:
interface Adder {
(num1: number, num2: number): number;
}
const add: Adder = function (a, b) {
return a + b;
};
Super Add
If you want your add function to handle more numbers, you can use a rest parameter... like this:
const add = function (...numbers: number[]) {
if (!numbers || !numbers.length) {
return 0;
}
return numbers
.reduce(function (acc, val) {
return acc + val;
});
};
console.log(add());
console.log(add(1, 2));
console.log(add(1, 2, 3, 4));
This will handle any number of arguments.