In TypeScript, you can define a function using the function
keyword, similar to JavaScript. TypeScript provides static typing, allowing you to specify the types of parameters and the return type of a function. Here's a basic example:
typescript// Function without explicit types
function add(x, y) {
return x + y;
}
// Function with explicit types
function addWithType(x: number, y: number): number {
return x + y;
}
In the above example, the add
function takes two parameters x
and y
without specifying their types, so TypeScript will infer them as any
. The addWithType
function, on the other hand, explicitly specifies that both parameters are of type number
and that the function returns a value of type number
.
You can also use arrow functions to define functions in TypeScript:
typescript// Arrow function without explicit types
const multiply = (x, y) => x * y;
// Arrow function with explicit types
const multiplyWithType = (x: number, y: number): number => x * y;
It's generally a good practice to provide explicit types for function parameters and return types to take advantage of TypeScript's static type checking and catch potential errors early in the development process.