Optional Parameters with '?'
Part of the Introduction To TypeScript section of Coddy's JavaScript journey — lesson 25 of 73.
Sometimes you want to create functions where certain parameters are not always required. TypeScript provides the ? syntax to mark parameters as optional, meaning callers can choose whether or not to provide them when calling the function.
To make a parameter optional, you add a question mark after the parameter name but before the type annotation:
function greet(name: string, greeting?: string): string {
if (greeting) {
return greeting + ", " + name;
}
return "Hello, " + name;
}In this example, name is required while greeting is optional. You can call this function with just the name (greet("Alice")) or with both parameters (greet("Alice", "Good morning")). Inside the function, optional parameters have the type string | undefined, so you should check if they exist before using them.
Challenge
EasyCreate a function named createUserProfile that takes two parameters: username of type string (required) and displayName of type string (optional). The function should return a string with an explicit return type annotation.
When both parameters are provided, the function should return: "Profile: [displayName] (@[username])"
When only the username is provided, the function should return: "Profile: @[username]"
Create another function named calculateDiscount that takes two parameters: price of type number (required) and membershipLevel of type string (optional). The function should return a number with an explicit return type annotation.
When both parameters are provided, the function should return the price reduced by 10% (multiply by 0.9).
When only the price is provided, the function should return the original price unchanged.
Test your functions by calling them with the following values and printing the results:
- Call
createUserProfilewith"john_doe"and"John Doe" - Call
createUserProfilewith only"jane_smith" - Call
calculateDiscountwith100and"premium" - Call
calculateDiscountwith only75
Print each result on a separate line in the order specified above.
Try it yourself
// TODO: Write your code here
// Create the createUserProfile function with proper type annotations
// Create the calculateDiscount function with proper type annotations
// Test the functions and print the resultsThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Introduction To TypeScript
1Getting Started with TS
What is TypeScript?Why Use TypeScript?Your First TypeScript CodeCompilation Process & ErrorsRecap: Introduction to TS4Working with Functions
Typing Params & Return ValuesTyping Arrow FunctionsThe 'void' Return TypeOptional Parameters with '?'Default Parameter ValuesTyping Rest ParametersDefining Function TypesRecap: Building Typed Funcs2Core Types
Basic Types: str, num, booleanThe 'any' Type: Escape HatchThe 'unknown' TypeWorking with 'null' & 'undef'Type Inference in ActionExplicit Type AnnotationsRecap: Core Types Practice5Types: Aliases, Unions & Inter
Type Aliases for PrimitivesUnion Types ('|')Working with Union TypesLiteral TypesIntersection Types ('&')Combining Type AliasesRecap: Advanced Type Combos3Data Structure: Arrays & Tuple
Typed Arrays'readonly' Modifier for ArraysWhat is a Tuple?Declaring and Accessing TuplesDestructuring TuplesReadonly TuplesMulti-dimensional Typed Arrays Spread Operator with ArraysRecap: Arrays and Tuples