Interfaces as function types in Typescript

Let’s get to know interfaces for functions - yes, that’s a thing.

We have seen interfaces used as types and interfaces as array types. Since function is an object and interfaces are supported on other objects, they should be supported on functions also. Right?

You betcha.

What is this blog if we can’t write about all the stuff that no one care’s about? Well, to be clear - I am not starting that trend today.

Let’s see an example of a simple function -

function getSum(x: number, y: number) {
  return x + y;
}

console.log(getSum(1, 2));
// 3

Imagine we have to support similar functions for all other million mathematical expressions. What are we going to do? Write a million types - never! We are no beasts.

We do something graceful using them interfaces and apply them to the function arguments.

interface twoNumOp {
  x: number;
  y: number;
}

function getSum(z: twoNumOp) {
  return z.x + z.y;
}

console.log(getSum({ x: 1, y: 2 }));
// 3

Quite neat - won’t you say? But, it can be much neater.

We will wrap the entire darn function with an interface so that it covers all the things required to support the million math operations.

interface twoNumOp {
  (x: number, y: number): void;
}

function getSum(x: number, y: number) {
  return x + y;
}

const summerOfAll: twoNumOp = getSum;
console.log(summerOfAll(1, 2));
// 3

The added advantage - you don’t go about changing function signatures for object oriented programming. That is so 2000s. Now, you just mask (interface) the non-OOP beauty.

Let’s say you have another function with a similar signature,

function getProd(x: number, y: number) {
  return x * y;
}

.. all you have to do is to apply signature..

const prodOfTwo: twoNumOp = getProd;
console.log(prodOfTwo(1, 2));
// 2

And, you are off to races (or wherever you go after you code a million math op’s).

comments powered by Disqus