TypeScript - 預設參數
Hello there, future coding superstars! Today, we're going to dive into the wonderful world of TypeScript and explore a feature that will make your life as a programmer much easier: Default Parameters. By the end of this lesson, you'll be wielding this powerful tool like a pro. So, let's get started!
What are Default Parameters?
Imagine you're a chef (bear with me, we'll get to the coding soon!). Every day, you make a delicious soup. Most of the time, you add salt to your soup. But sometimes, a customer might ask for no salt. Wouldn't it be great if you could have a recipe that automatically includes salt unless specified otherwise? That's exactly what default parameters do in programming!
In TypeScript, default parameters allow you to set a default value for a function parameter. If the function is called without providing a value for that parameter, the default value will be used.
Let's look at a simple example:
function greet(name: string = "World") {
console.log(`Hello, ${name}!`);
}
greet(); // Output: Hello, World!
greet("Alice"); // Output: Hello, Alice!
In this example, "World"
is the default parameter for name
. If we call greet()
without any arguments, it uses "World" as the default. But if we provide a name, like "Alice", it uses that instead.
Why Use Default Parameters?
- Flexibility: They make your functions more flexible, allowing them to work with or without certain arguments.
- Cleaner Code: They reduce the need for conditionals inside your function to check if a parameter was provided.
- Improved Readability: Default parameters make it clear what the expected "normal" values are for a function.
How to Use Default Parameters
Let's dive deeper with more examples:
Basic Usage
function calculateArea(width: number = 10, height: number = 5) {
return width * height;
}
console.log(calculateArea()); // Output: 50
console.log(calculateArea(20)); // Output: 100
console.log(calculateArea(7, 3)); // Output: 21
In this example, both width
and height
have default values. We can call the function with no arguments, one argument (which will be used for width
), or both arguments.
Using Expressions as Default Values
Default parameters can be expressions, not just simple values:
function getRandomGreeting(name: string = "friend", time: Date = new Date()) {
const greetings = ["Hello", "Hi", "Hey", "Howdy"];
const randomGreeting = greetings[Math.floor(Math.random() * greetings.length)];
return `${randomGreeting}, ${name}! It's ${time.toLocaleTimeString()} now.`;
}
console.log(getRandomGreeting()); // Output: e.g., "Hey, friend! It's 3:45:30 PM now."
console.log(getRandomGreeting("Alice")); // Output: e.g., "Hello, Alice! It's 3:45:35 PM now."
Here, we're using new Date()
as a default value for time
, which will give us the current date and time when the function is called.
Default Parameters with Other Types
Default parameters work with all types in TypeScript:
function createUser(
name: string = "Anonymous",
age: number = 0,
isAdmin: boolean = false,
hobbies: string[] = []
) {
return { name, age, isAdmin, hobbies };
}
console.log(createUser());
// Output: { name: "Anonymous", age: 0, isAdmin: false, hobbies: [] }
console.log(createUser("Alice", 30, true, ["reading", "coding"]));
// Output: { name: "Alice", age: 30, isAdmin: true, hobbies: ["reading", "coding"] }
This example shows how default parameters can be used with different types, including arrays and booleans.
Optional Parameters vs. Default Parameters
Now, you might be thinking, "Wait a minute! I've heard of optional parameters. How are they different from default parameters?" Great question! Let's break it down:
Optional Parameters
Optional parameters are marked with a ?
and allow you to call a function without providing a value for that parameter.
function greetOptional(name?: string) {
if (name) {
console.log(`Hello, ${name}!`);
} else {
console.log("Hello, stranger!");
}
}
greetOptional(); // Output: Hello, stranger!
greetOptional("Bob"); // Output: Hello, Bob!
Default Parameters
Default parameters provide a default value that will be used if no argument is provided.
function greetDefault(name: string = "stranger") {
console.log(`Hello, ${name}!`);
}
greetDefault(); // Output: Hello, stranger!
greetDefault("Bob"); // Output: Hello, Bob!
Key Differences
Feature | Optional Parameters | Default Parameters |
---|---|---|
Syntax | Uses ? after parameter name |
Uses = value after parameter type |
When no argument is provided | Parameter is undefined
|
Parameter uses the default value |
Need for null checks | Often requires checks in function body | No additional checks needed |
Clarity of intent | Less clear what happens if parameter is omitted | Clearly shows the default behavior |
In general, default parameters are often more convenient and lead to cleaner code, as they remove the need for null checks inside the function body.
Best Practices for Using Default Parameters
- Use Meaningful Defaults: Choose default values that make sense for most use cases of your function.
- Document Your Defaults: Even though the default is in the code, it's good practice to mention it in your function's documentation.
- Be Careful with Mutable Defaults: Avoid using mutable objects as default parameters, as they can lead to unexpected behavior.
-
Consider Undefined: Remember that
undefined
will trigger the default value, butnull
won't.
function exampleBestPractices(
requiredParam: string,
optionalParam: string = "default value",
anotherOptional: number = 42
) {
// Function body
}
Conclusion
And there you have it, folks! You've just leveled up your TypeScript skills by mastering default parameters. Remember, like any tool in programming, default parameters are most powerful when used judiciously. They can make your code more robust, readable, and flexible.
As you continue your coding journey, you'll find many opportunities to use default parameters. Maybe you'll create a function to calculate shipping costs with a default shipping method, or a function to format dates with a default format string. The possibilities are endless!
Keep practicing, keep coding, and most importantly, keep having fun with TypeScript. Until next time, happy coding!
Credits: Image by storyset