0
0
Typescriptprogramming~5 mins

typeof type guards in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a typeof type guard in TypeScript?

A typeof type guard is a way to check the type of a variable at runtime using the typeof operator. It helps TypeScript narrow down the type inside conditional blocks.

Click to reveal answer
beginner
How does typeof help with type safety in TypeScript?

By checking the type of a variable with typeof, TypeScript can safely allow operations specific to that type inside the guarded block, preventing errors.

Click to reveal answer
beginner
Example: What does this code do?<br>
if (typeof value === 'string') {<br>  console.log(value.toUpperCase());<br>}

This code checks if value is a string. Inside the if block, TypeScript knows value is a string, so calling toUpperCase() is safe.

Click to reveal answer
intermediate
Which types can typeof check in TypeScript?

typeof can check primitive types like 'string', 'number', 'boolean', 'bigint', 'symbol', 'undefined', and 'object' (including null).

Click to reveal answer
intermediate
Why can't typeof distinguish between null and object?

Because in JavaScript, typeof null returns 'object'. So typeof cannot differentiate null from other objects.

Click to reveal answer
What does typeof return for a string variable?
A'text'
B'char'
C'string'
D'str'
Which of these is NOT a valid typeof result in JavaScript/TypeScript?
A'undefined'
B'boolean'
C'number'
D'array'
Why use typeof type guards in TypeScript?
ATo check variable types at runtime and narrow types safely
BTo declare new types
CTo convert types automatically
DTo create classes
What will typeof null return?
A'object'
B'undefined'
C'null'
D'boolean'
Which code snippet correctly uses a typeof type guard?
Aif (typeof x === 'stringify') { console.log(x); }
Bif (typeof x === 'number') { console.log(x.toFixed(2)); }
Cif (typeof x === 'integer') { console.log(x); }
Dif (typeof x === 'array') { console.log(x.length); }
Explain how typeof type guards help TypeScript understand variable types.
Think about how checking a variable's type at runtime helps avoid errors.
You got /4 concepts.
    List the primitive types that typeof can detect and mention one limitation.
    Recall the common JavaScript types and the quirk with null.
    You got /8 concepts.