TypeScript Call Signatures (original) (raw)
Last Updated : 22 Jan, 2025
**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; // Call signature
propertyName: PropertyType; // Additional property
};
**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
TypeScript ``
type GreetingFunction = { (name: string): string; // Call signature description: string; // Additional property };
const greet: GreetingFunction = (name: string) => {
return Hello, ${name}!
;
};
greet.description = "A function to greet users";
console.log(greet("Alice"));
console.log(greet.description);
``
- 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.
**Output:
Hello, Alice!
A function to greet users
Calculator Using Call Signature
TypeScript ``
type Calculator = { (a: number, b: number): number; // Call signature operation: string; // Additional property };
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)}
);
``
- 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.
**Output:
Addition: 8
Multiplication: 15
Best Practices for Using TypeScript Call Signatures
- **Clearly Define Parameter and Return Types: Ensure all call signatures specify explicit parameter and return types for better type safety.
- **Include Descriptive Properties: Add properties that provide context or metadata about the callable object to enhance code readability.
- **Use Consistent Naming Conventions: Adopt clear and consistent naming for callable objects and their properties to improve maintainability.