乐闻世界logo
搜索文章和话题

How can you define a function with optional parameters in TypeScript?

1个答案

1

Defining a function with optional parameters in TypeScript is done by adding a question mark ? after the parameter name. This indicates that the parameter is optional and can be omitted when calling the function.

Here is a concrete example:

typescript
function greet(name: string, age?: number): string { if (age !== undefined) { return `Hello, my name is ${name} and I am ${age} years old.`; } else { return `Hello, my name is ${name}.`; } } // Usage example console.log(greet("Alice", 30)); // Output: Hello, my name is Alice and I am 30 years old. console.log(greet("Bob")); // Output: Hello, my name is Bob.

In this example, the greet function accepts two parameters: name and age. Here, name is a required parameter, while age is an optional parameter. When calling the greet function, you can provide only the name parameter or both name and age parameters. If the age parameter is provided, the output includes the age information; otherwise, it does not include the age information.

This approach enhances the flexibility and applicability of the function.

2024年7月29日 13:51 回复

你的答案