What does an interface with multiple call signatures mean in typescript?

Advertisements

I was reading the typescript handbook in the documentation, and I stopped on the section Call Signatures

They say, if you want to define a function which has properties on it, you can do it this way:

type DescribableFunction = {
  description: string;
  (someArg: number): boolean;
};
function doSomething(fn: DescribableFunction) {
  console.log(fn.description + " returned " + fn(6));
}
const x: DescribableFunction = (arg: number) => true
x.description = "always return true"
doSomething(x)

My question is about the interface:

type DescribableFunction = {
    description: string;
    (someArg: number): boolean;
};

What if you define this interface this way?

type DescribableFunction = {
    description: string;
    (someArg: number): boolean;
    (someArg: string): void;
    (someArg: Date): number;
    (someArg: number | string): string
};

When writing this interface alone, typescript doesn’t complain, but it does when you add the rest of the code. So it’s a valid syntax.

But what does this syntax mean?

>Solution :

You can define multiple call signatures using function overloading in TypeScript, but in that case, each call signature must have a unique parameter list.

Here’s an example of function overloading that will work:

type DescribableFunction = {
description: string;
(someArg: number): boolean;
(someArg: string): void;
(someArg: Date): number;
};

function fn(x: number): boolean;
function fn(x: string): void;
function fn(x: Date): number;
function fn(x: number | string | Date): boolean | void | number {
if (typeof x === "number") {
return true;
} else if (typeof x === "string") {
console.log(x);
} else {
return x.getTime();
}
}

const df: DescribableFunction = fn;
df.description = "example";
console.log(df(1)); // logs true
console.log(df("test")); // logs "test"
console.log(df(new Date())); // logs current timestamp

Leave a ReplyCancel reply