0

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?

4
  • Because you're setting a type for calc (foo: type), not assigning a value (foo = value). Commented Apr 24, 2017 at 21:15
  • ahh I get what you mean now! i am not assigning the function to the function type variable @jonrsharpe Commented Apr 24, 2017 at 21:16
  • 1
    Shouldn't be it let calc = (value1: number, value2: number) => value1 * value2? Commented Apr 24, 2017 at 21:17
  • 2
    You're not actually creating a function. You're defining a type. I don't really know how else to put it. Commented Apr 24, 2017 at 21:18

2 Answers 2

5

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;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, yeah I understood it. :)
1

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);
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.