Challenge your understanding of TypeScript variables, type declarations, and the differences between fundamental data types. This interactive quiz covers important concepts such as variable initialization, assignment, and common typing pitfalls in TypeScript, designed for effective learning and review.
Which of the following is the correct way to declare a typed variable holding a number value in TypeScript?
Explanation: The correct syntax for declaring a typed variable in TypeScript is 'let age: number = 25;'. Option B uses incorrect syntax by placing the keyword 'number' in the wrong place. Option C uses 'num' instead of the correct 'number' type. Option D leaves out the colon, which is required for type annotation.
What type will TypeScript infer for the variable declared as 'let isActive = false;'?
Explanation: TypeScript infers the variable 'isActive' as a boolean since it is initialized with the boolean value 'false'. Option B, 'any', only occurs without an assignment or an explicit type. Option C, 'string', would require a string value, and Option D, 'undefined', applies if no value is assigned.
If a variable is declared with the 'unknown' type, what must a developer do before assigning it to a variable with a specific type?
Explanation: When using the 'unknown' type, developers are required to perform a type assertion or runtime type check before assigning its value to another typed variable. Assigning directly without a check (option B) is disallowed for safety reasons. Option C, converting with JSON.stringify(), is irrelevant and does not change the variable type. Option D is incorrect, as 'unknown' can be used with any type, not just arrays.
What happens if you try to reassign a variable defined with 'const' in TypeScript?
Explanation: Reassigning a variable declared with 'const' results in a compile-time error, as 'const' marks variables as immutable. Option B is incorrect since TypeScript enforces immutability at compile time. Option C, becoming undefined, is not the case for reassigned constants. Option D's statement about strict mode is incorrect; immutability applies regardless of mode.
Given 'let username: string;', what happens if you assign null to 'username' without enabling strictNullChecks?
Explanation: Without 'strictNullChecks' enabled, TypeScript allows 'null' to be assigned to variables of type 'string', treating 'null' and 'undefined' as valid values. Option B is incorrect because the error only occurs when 'strictNullChecks' is enabled. Option C is wrong since the assignment does take effect. Option D is incorrect, as both 'null' and 'undefined' can be assigned without strict null checks.