Typescript functions
Created By: chatGPT
TypeScript functions are blocks of code designed to perform a particular task. They can take input parameters and return an output. With TypeScript, you can define the types of parameters and the return type, making your code more robust and less prone to errors. Here are some basic examples of how to define and use functions in TypeScript.
function greet(name: string): string {
return `Hello, ${name}!`;
}
const greeting = greet('Alice');
console.log(greeting); // Output: Hello, Alice!
Optional parameters in functions can be specified by adding a question mark
?
after the parameter name. This allows you to call the function without providing the argument for that parameter.function greet(name: string, age?: number): string {
return age ? `Hello, ${name}. You are ${age} years old!` : `Hello, ${name}!`;
}
console.log(greet('Bob')); // Output: Hello, Bob!
console.log(greet('Bob', 30)); // Output: Hello, Bob. You are 30 years old!
You can also use default parameters. A default parameter uses a default value if no argument is provided.
function greet(name: string, age: number = 20): string {
return `Hello, ${name}. You are ${age} years old!`;
}
console.log(greet('Charlie')); // Output: Hello, Charlie. You are 20 years old!
console.log(greet('Charlie', 25)); // Output: Hello, Charlie. You are 25 years old!
You can define function types to specify the signature that a function should adhere to. This can be particularly useful when passing functions as arguments.
function add(x: number, y: number): number {
return x + y;
}
let myFunction: (a: number, b: number) => number;
myFunction = add;
console.log(myFunction(5, 10)); // Output: 15
Arrow functions provide a more concise syntax for writing functions and do not bind their own
this
. They are especially useful in callbacks.const multiply = (a: number, b: number): number => {
return a * b;
};
console.log(multiply(5, 4)); // Output: 20
In TypeScript, you can also define functions that return promises, which is particularly useful for asynchronous operations, such as API calls.
async function fetchData(url: string): Promise<Response> {
const response = await fetch(url);
return response;
}
fetchData('https://api.example.com/data')
.then(response => console.log(response));