Explore your understanding of working with enums and tuples in TypeScript, including declaration, usage, and best practices. This quiz covers fundamental concepts, syntax, and scenarios related to these two powerful TypeScript types.
Which of the following correctly defines a numeric enum for representing days of the week in TypeScript?
Explanation: The correct answer uses the enum keyword followed by curly braces and comma-separated identifiers for each day. The second option mistakenly uses tuple syntax, which is not valid for enums. The third option is an array definition, not an enum. The fourth option incorrectly uses an assignment and string values, which does not follow the syntax for defining enums in TypeScript.
Given the tuple declaration let user: [string, number] = ['Alice', 42], what is the result of user[1]?
Explanation: user[1] refers to the second element of the tuple, which is the number 42 in this case. 'Alice' is the value at user[0], not user[1]. The value is not a string, so '42' is incorrect. undefined would be returned if the index did not exist, which is not the case here.
What does the following code output: enum Color { Red, Green, Blue }; console.log(Color[1]);
Explanation: In TypeScript, numeric enums generate a reverse mapping, so Color[1] returns 'Green'. The answer '1' is incorrect because that's the key, not the value. The option with single quotes, 'Green', misrepresents the fact that console.log displays the string without quotes. undefined would occur only if there was no match for the key 1.
How can you add an additional number to the end of the tuple let point: [number, number] = [5, 10]; in TypeScript?
Explanation: The push method is the standard way to append an element to an array or tuple in JavaScript and TypeScript. The add and append methods do not exist on arrays or tuples, making them incorrect. Assigning directly to point[point.length] can technically work but is less standard and undermines tuple type safety in TypeScript.
What is one key difference between string enums and numeric enums in TypeScript?
Explanation: Numeric enums in TypeScript provide reverse mapping (from value to name), but string enums do not provide this feature. Both types can be iterated, so the second option is incorrect. Numeric enums can start from any number, not just zero. The case of enum names is not restricted as in the last distractor.