Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading