Typescript optional parameters
Created By: chatGPT
In TypeScript, you can define optional parameters in functions by using the
?
suffix with the parameter name. This allows you to call the function without providing values for those parameters. If the caller does not supply an argument for an optional parameter, its value will be undefined
by default.function greet(name?: string) {
if (name) {
console.log(`Hello, ${name}!`);
} else {
console.log(`Hello, guest!`);
}
}
greet(); // Output: Hello, guest!
greet('Alice'); // Output: Hello, Alice!
You can also combine optional parameters with default parameters. By providing a default value for an optional parameter, you can ensure the parameter has a defined value even if no argument is passed.
function greet(name: string = 'guest') {
console.log(`Hello, ${name}!`);
}
greet(); // Output: Hello, guest!
greet('Bob'); // Output: Hello, Bob!
When defining functions with multiple parameters, you can mix optional and required parameters, but all required parameters must come before any optional ones. This helps enforce clarity when calling the function.
function createUser(username: string, email: string, age?: number) {
console.log(`User created: ${username}, Email: ${email}, Age: ${age}`);
}
createUser('johnDoe', 'john@example.com'); // Output: User created: johnDoe, Email: john@example.com, Age: undefined
createUser('janeDoe', 'jane@example.com', 30); // Output: User created: janeDoe, Email: jane@example.com, Age: 30
While using optional parameters can make your code flexible, it’s good practice to handle the undefined case appropriately, such as by using conditional statements or ternary operators to provide a fallback.
function introduce(person: { name: string; age?: number }) {
console.log(`I'm ${person.name} and I'm ${person.age !== undefined ? person.age : 'age not provided'}.`);
}
introduce({ name: 'Alice' }); // Output: I'm Alice and I'm age not provided.
introduce({ name: 'Bob', age: 25 }); // Output: I'm Bob and I'm 25.