Reputation: 53
here I'm trying to add two numbers using typescript interfaces and arrow functions concept. when I'm running the compiled js code it is calling add() method and it is displaying NaN.
below is the ts code:- var add = (Num) => console.log(Num.num1 + Num.num2) ;
interface Num {
num1: number;
num2: number;
}
this.add(1,2);
below is the js code:-
var add = function (Num) { return console.log(Num.num1 + Num.num2); };
this.add(1, 2);
Thanks in advance
Upvotes: 1
Views: 2877
Reputation: 250922
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); };
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.
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 });
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;
};
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.
Upvotes: 3
Reputation: 1672
You defined a function add()
that accept a parameter of type Num, but you're actually passing it two number, not a Num.
So simply change your call to
add({num1: 1, num2: 2});
which is an object with the props you want. Hope it helps
Upvotes: 2
Reputation: 171
this.add({ num1: 1, num2: 2 });
- that is the point.
In your code you pass two params (1 and 2), function expects only one (Num). So you have to pass values as Num object.
Upvotes: 1