Explore key concepts of TypeScript functions and their parameters with this quiz, designed to challenge your understanding of function types, default and optional parameters, rest parameters, and function overloading. Ideal for those looking to strengthen their TypeScript skills in a technical context.
Which of the following is the correct way to define a TypeScript function accepting two numbers and returning a number?
Explanation: The correct syntax requires both parameters and the return value to be explicitly typed with 'number' in TypeScript. The second option is incorrect because TypeScript uses lowercase 'number', not 'Number', and lacks parameter types. Option three uses 'num' instead of 'number', which is not valid. The fourth option uses 'void' as the return type, which means the function doesn't return anything.
What result does the following function call produce: add(5), given function add(a: number, b?: number) { return a + (b || 0); }?
Explanation: When 'add(5)' is called, 'b' is undefined, so the expression 'b || 0' evaluates to 0, resulting in 5. The second option is incorrect since undefined + number is not NaN in this context. The third is wrong because optional parameters do not cause errors if omitted. The fourth option is inaccurate because the function returns a number, not undefined.
How do rest parameters behave in the following TypeScript function: function total(...nums: number[]) { return nums.reduce((a, b) =u003E a + b, 0); }?
Explanation: Rest parameters let you pass any number of arguments, which are grouped into an array named 'nums'. The second option is wrong because there is no restriction on the number of arguments. The third option is incorrect as rest parameters can accept zero or more values. The last option is incorrect since rest parameters collect individual values into an array.
What value will be returned by outputMessage('Hi'), given function outputMessage(message: string, sender: string = 'Admin') { return `${sender}: ${message}`; }?
Explanation: If 'sender' is not provided, the default value 'Admin' is used, so the function returns 'Admin: Hi'. 'undefined: Hi' would only occur if no default value was set. 'Hi: Admin' reverses the values and so is incorrect. The function does not throw an error because 'sender' is not a required parameter.
In TypeScript, what does function overloading allow you to do?
Explanation: Function overloading allows declaring multiple type signatures for a single function, enabling different argument types or counts. The second option is wrong as TypeScript does not allow multiple separate bodies for the same function name. Anonymous functions are unrelated to overloading, making the third option incorrect. The fourth option is not accurate, as function overloading relates to signatures, not parameter optionality.