Typescript parameters
Created By: chatGPT
Parameters in TypeScript functions help you define the expected types of values that can be passed to the function, enhancing the type safety of your code. Here's how you can define function parameters with specified types.
function greet(name: string): string {
return `Hello, ${name}!`;
}
You can also define optional parameters by appending a question mark (
?
) to the parameter's name. This indicates that the parameter is not required during the function call.function greet(name: string, age?: number): string {
const ageInfo = age ? ` You are ${age} years old.` : '';
return `Hello, ${name}!${ageInfo}`;
}
If you want to define default parameters, you can assign a default value to them. If no value is passed, the default value will be used.
function greet(name: string, age: number = 25): string {
return `Hello, ${name}! You are ${age} years old.`;
}
Rest parameters allow you to pass an arbitrary number of arguments to a function. This is done by prefixing the parameter with
...
.function sum(...numbers: number[]): number {
return numbers.reduce((total, num) => total + num, 0);
}
You can also enforce stricter types using tuples instead of arrays, which allows you to specify different types for each parameter.
function displayInfo(...info: [string, number]): string {
return `Name: ${info[0]}, Age: ${info[1]}`;
}