What we'll cover
TypeScript enhances JavaScript's functions with powerful type safety features. In this guide, we'll explore:
- How to add type annotations to function parameters
- Defining return types for precise output control
- Working with optional and default parameters
- Creating standalone function type definitions
Parameter types
When defining a function, you can specify the data type for each parameter by adding a colon and the type after the parameter name. These type annotations help catch errors by ensuring that only values of the correct type are passed to the function.
function greet(noun: string) {
console.log(`Hello, ${noun}!`);
greet('World'); // Prints: Hello, World
greet(2020); // Argument of type 'number' is not assignable to parameter of type 'string'.
}
Optional parameter
TypeScript lets you make function parameters optional by adding a question mark (?) after the parameter name. When a parameter is marked as optional, you can call the function without providing a value for that parameter. For example:
function greet(name: string, title?: string) {
if (title) {
return `Hello ${title} ${name}`;
}
return `Hello ${name}`;
}
// Both calls are valid
greet("Alice", "Ms."); // "Hello Ms. Alice"
greet("Bob"); // "Hello Bob"
Optional parameters must come after required parameters - TypeScript will throw an error if you put required parameters after optional ones
Default parameters
When you provide a default value for a function parameter in TypeScript, the compiler automatically infers the parameter's type based on the default value's type. For example:
function greet(name = "World") {
// TypeScript infers 'name' is type string
return `Hello ${name}`;
}
greet(); // Works: uses default "World"
greet("Alice"); // Works: "Alice" is a string
greet(123); // Error: number is not assignable to string
Inferring return types
By looking at the types of the values in a function’s return statement, TypeScript can infer the return type of a function.
function factOrFiction() {
return Math.random() >= .5 ? 'true' : 'false';
}
const myAnswer : boolean = factOrFiction(); // Type 'string' is not assignable to type 'boolean'
Try some examples in TypeScript's playground with instant live preview
Void return type
If a function does not return any value, then you can specify void as a return type using type annotation.
function sayHello(): void {
console.log('Hello!')
}
Explicit return types
You can specify a function's return type in TypeScript by adding a colon and type after the parameter parentheses. For example:
function multiply(x: number, y: number): number {
return x * y;
}
function getGreeting(name: string): string {
return `Hello ${name}`;
}
This explicit return type annotation helps catch errors and makes your code's intent clearer. TypeScript will verify that all return statements in the function match the declared return type.
Function type definitions
In TypeScript, you can create reusable function types that define the expected parameters and return types. This is especially useful when you have multiple functions that share the same signature, or when you want to define the shape of callback functions.
There are two ways to define function types:
typescriptCopy// Using type alias
type CalculateFunction = (x: number, y: number) => number;
// Using interface
interface SearchFunction {
(query: string, limit?: number): string[];
}
// Using these type definitions
const add: CalculateFunction = (x, y) => x + y;
const subtract: CalculateFunction = (x, y) => x - y;
const search: SearchFunction = (query, limit = 10) => {
// Implementation here
return [`Results for: ${query}`];
};
This is particularly valuable when:
- Working with callbacks and event handlers
- Creating libraries or APIs where functions are passed as parameters
- Maintaining consistency across related functions
- Reducing code duplication in type annotations
Avoid using the type 'any', although it may be tempting at times to get rid of Typescript's complaints with your code.
Key takeaways
- TypeScript enhances function type safety by allowing you to explicitly declare parameter and return types.
- Optional parameters are marked with a ? and can be omitted when calling the function.
- Default parameters automatically infer their type from the default value provided.
- Function return types are specified after the parameter list using : type
- Type annotations help catch errors early and serve as inline documentation for your code.
- Standalone function types can be created using type or interface for reusable function signatures
Further resources
Try TypeScript's playground with instant live preview and console
Look at TypeScript's documentation on functions
What to learn next?
Mastered TypeScript functions? Explore these topics next:
Function overloads: how to define multiple signatures for a single function
Interfaces and types: my article breaking down this subject
You might be interested, if you have limited time to learn code/are a career-changer, in this article.
Top comments (0)