0
0
Typescriptprogramming~5 mins

Type narrowing with typeof in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does typeof do in TypeScript?

typeof checks the type of a variable at runtime and helps TypeScript narrow down the variable's type for safer code.

Click to reveal answer
beginner
How does TypeScript use typeof for type narrowing?

TypeScript uses typeof in conditional checks to understand the exact type of a variable inside that block, allowing safer operations.

Click to reveal answer
beginner
Example: What type does TypeScript narrow x to inside this block?<br>
if (typeof x === 'string') { /* here */ }

Inside the if block, TypeScript knows x is a string.

Click to reveal answer
intermediate
Can typeof narrow types other than string?

Yes, typeof can narrow types like number, boolean, undefined, object, and function.

Click to reveal answer
beginner
Why is type narrowing useful in TypeScript?

It helps avoid errors by letting TypeScript know the exact type, so you can safely use properties or methods specific to that type.

Click to reveal answer
What does typeof x === 'number' check?
AIf x is undefined
BIf x is a string
CIf x is a number
DIf x is an object
Inside if (typeof y === 'boolean'), what type does TypeScript treat y as?
Astring
Bany
Cnumber
Dboolean
Which of these is NOT a valid typeof result in JavaScript/TypeScript?
A'array'
B'number'
C'string'
D'boolean'
What happens if you try to access a string method on a variable not narrowed to string?
ATypeScript gives an error
BTypeScript allows it without error
CJavaScript crashes
DThe code runs slower
Which keyword helps TypeScript narrow types at runtime?
Alet
Btypeof
Cvoid
Dinstanceof
Explain how typeof helps with type narrowing in TypeScript.
Think about how checking a variable's type lets TypeScript know what it can safely do.
You got /4 concepts.
    List the common types that typeof can check in TypeScript.
    Remember the basic JavaScript types that typeof returns.
    You got /6 concepts.