TypeScript Call Signatures
TypeScript call signatures define the parameter types and return types for function-like objects, enabling the creation of callable entities with additional properties.
- Allow objects to be invoked as functions while possessing properties.
- Enhance code flexibility by combining callable behavior with structured data.
Syntax:
type MyCallableObject = {
(parameter1: Type1, parameter2: Type2): ReturnType;
propertyName: PropertyType;
};
Parameters:
- MyCallableObject: The name of the type alias for the callable object.
- (parameter1: Type1, parameter2: Type2): Defines the parameters and their types for the callable aspect.
- ReturnType: Specifies the return type of the callable function.
- propertyName: PropertyType: An example of an additional property within the object.
Greeting Function Using Call Signature
Call signatures allow us to define a function type that is both callable like a function and can also have additional properties. This is useful when you want a function to carry extra information along with its callable behavior.
Now letâs understand with the help of an example:
type GreetingFunction = {
(name: string): string;
description: string;
};
const greet: GreetingFunction = (name: string) => {
return `Hello, ${name}!`;
};
greet.description = "A function to greet users";
console.log(greet("Alice"));
console.log(greet.description);
Output:
Hello, Alice!
A function to greet users
In this example:
- GreetingFunction defines a callable object that takes a string and returns a string.
- The greet function implements this call signature and includes an additional description property.
Calculator Using Call Signature
A call signature can define functions with parameters while also attaching descriptive properties.
Now letâs understand with the help of an example:
type Calculator = {
(a: number, b: number): number;
operation: string;
};
const add: Calculator = (a: number, b: number) => a + b;
add.operation = "Addition";
const multiply: Calculator = (a: number, b: number) => a * b;
multiply.operation = "Multiplication";
console.log(`${add.operation}: ${add(5, 3)}`);
console.log(`${multiply.operation}: ${multiply(5, 3)}`);
Output:
Addition: 8
Multiplication: 15
In this example:
- Calculator defines a callable object that takes two number parameters and returns a number.
- The add and multiply functions implement this call signature with specific operations and include an operation property describing the operation.