Harry
Harry

Reputation: 3205

How to use Function types in TypeScript

I am trying to understand how to use "Function types".

Let's say we have the following:

function calSum(val1: number, val2: number): number{
    return val1 * val2;
}
console.log(calSum(10,20)); //prints 200

Now let's say we have:

let calc: (value1: number, value2: number) => number;

if I do the following:

calc(10,20);

I would expect to see 200, however I get following error:

Uncaught TypeError: calFuncType is not a function

I would like to understand why this is, and how to use this type?

Upvotes: 0

Views: 685

Answers (2)

sbking
sbking

Reputation: 7680

In your example, calSum is a concrete implementation of your function, while calc is a variable that has not been assigned to anything yet, so it is undefined. You have specified the type of value that calc can hold, but you haven't actually given it a value yet.

I think what you might be looking for is how to define an interface for a function, and then implementing that interface. For example:

interface CalcFunction {
  (value1: number, value2: number): number;
}

let multiply: CalcFunction = (a, b) => a * b;
let add: CalcFunction = (a, b) => a + b;

let product: number = multiply(3, 5);
let sum: number = add(3, 5);

console.log(product); // 15
console.log(sum); // 8

TypeScript will know that both multiply and add take two number arguments and return a number because they both explicitly implement the CalcFunction interface.

Then, for example, you could do something like this:

let calculate = (calc: CalcFunction, a: number, b: number): number => {
  return calc(a, b);
}

Upvotes: 1

Nitzan Tomer
Nitzan Tomer

Reputation: 164357

This:

let calc: (value1: number, value2: number) => number;

Compiles into:

let calc;

That is, you only declared a variable with a name, but you haven't assign a value to it.

This is how to assign a value to it:

let calc: (value1: number, value2: number) => number = function(val1: number, val2: number): number{
    return val1 * val2;
}

The compiler can infer types, so this should be enough:

let calc = function(val1: number, val2: number): number{
    return val1 * val2;
}

Or, using arrow functions:

let calc = (val1: number, val2: number) => val1 * val2;

Upvotes: 5

Related Questions