0
0
Typescriptprogramming~5 mins

Optional parameters in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is an optional parameter in TypeScript?
An optional parameter is a function parameter that may or may not be provided when the function is called. It is marked with a question mark (?) after the parameter name.
Click to reveal answer
beginner
How do you declare an optional parameter in a TypeScript function?
You add a question mark (?) after the parameter name in the function definition, like <code>function greet(name?: string)</code>.
Click to reveal answer
beginner
What happens if you call a function without providing an optional parameter?
The optional parameter is undefined inside the function, so you can check if it was provided or not.
Click to reveal answer
intermediate
Can optional parameters be followed by required parameters in TypeScript?
No, optional parameters must come after all required parameters in the function signature.
Click to reveal answer
beginner
Example: What is the output of this code?<br><pre>function sayHi(name?: string) {<br>  console.log(`Hi, ${name ?? 'friend'}!`);<br>}<br>sayHi();<br>sayHi('Anna');</pre>
The output is:<br>
Hi, friend!<br>Hi, Anna!
<br>Because when no name is given, it uses 'friend' as a default message.
Click to reveal answer
How do you mark a parameter as optional in TypeScript?
AUse the keyword 'optional' before the parameter
BAdd an exclamation mark (!) after the parameter name
CUse the keyword 'maybe' before the parameter
DAdd a question mark (?) after the parameter name
What is the type of an optional parameter if it is not provided when calling the function?
Aundefined
Bnull
Cempty string
Dzero
Which of these function signatures is valid in TypeScript?
Afunction f(a?: number, b: string)
Bfunction f(a: number, b?: string)
Cfunction f(a?: number, b?: string, c: boolean)
Dfunction f(a: number, b: string, c?: boolean, d: number)
What will this code print?<br>
function greet(name?: string) {<br>  console.log(name || 'Guest');<br>}<br>greet();
Aundefined
BError
CGuest
Dnull
Can you have multiple optional parameters in a TypeScript function?
AYes, as long as they are at the end of the parameter list
BNo, only one optional parameter is allowed
CYes, but they must be separated by required parameters
DNo, optional parameters are not supported
Explain how to use optional parameters in TypeScript functions and why they are useful.
Think about how to make some inputs to a function not mandatory.
You got /4 concepts.
    Describe the rules about the order of optional and required parameters in TypeScript function definitions.
    Consider what happens if you put an optional parameter before a required one.
    You got /3 concepts.