Type narrowing is the process where TypeScript reduces a variable's possible types to a more specific one based on checks or conditions in the code.
Click to reveal answer
beginner
Why do we need type narrowing in TypeScript?
We need type narrowing to safely access properties or methods of a variable when it can have multiple types, preventing errors and improving code safety.
Click to reveal answer
intermediate
How does type narrowing help prevent runtime errors?
By checking a variable's type before using it, TypeScript ensures only valid operations run, avoiding errors like calling a method on an undefined or wrong type.
Click to reveal answer
beginner
Give an example of a type narrowing check in TypeScript.
Using an if statement like if (typeof value === 'string') narrows the type of value to string inside the block.
Click to reveal answer
intermediate
What happens if you don't use type narrowing when needed?
Without narrowing, TypeScript may show errors or allow unsafe code that can cause bugs or crashes when the program runs.
Click to reveal answer
What does type narrowing do in TypeScript?
ARemoves types from variables
BChanges the variable's value automatically
CConverts all types to string
DMakes a variable's type more specific based on checks
✗ Incorrect
Type narrowing makes the variable's type more specific after checking conditions.
Why is type narrowing important?
ATo convert types to numbers
BTo make code run faster
CTo prevent runtime errors by ensuring safe operations
DTo hide errors from the developer
✗ Incorrect
Type narrowing helps avoid errors by confirming the variable's type before use.
Which of these is a common way to narrow types?
AUsing if statements with typeof checks
BUsing console.log statements
CDeclaring variables without types
DIgnoring type errors
✗ Incorrect
Using if statements with typeof or instanceof checks narrows types safely.
What happens if you try to access a property without narrowing a union type?
AThe code always works fine
BTypeScript shows an error or warning
CThe property is ignored
DThe variable changes type automatically
✗ Incorrect
TypeScript prevents unsafe access by showing errors if types are not narrowed.
Which keyword helps TypeScript narrow types inside a condition?
Atypeof
Bvar
Cfunction
Dclass
✗ Incorrect
The typeof operator is used to check and narrow primitive types.
Explain why type narrowing is needed in TypeScript and how it improves code safety.
Think about what happens when a variable can be many types.
You got /4 concepts.
Describe a simple example of type narrowing using an if statement in TypeScript.
Use typeof to check if a variable is a string or number.
You got /4 concepts.
Practice
(1/5)
1. Why do we need type narrowing in TypeScript when a variable can have multiple types?
easy
A. To tell TypeScript the exact type so it can check code safety
B. To make the code run faster at runtime
C. To allow variables to change types dynamically
D. To avoid writing any type annotations
Solution
Step 1: Understand the role of type narrowing
Type narrowing helps TypeScript know the exact type of a variable at a certain point in code.
Step 2: Recognize the benefit for code safety
Knowing the exact type allows TypeScript to check for errors and prevent bugs before running the code.
Final Answer:
To tell TypeScript the exact type so it can check code safety -> Option A
Quick Check:
Type narrowing = safer code [OK]
Hint: Type narrowing means telling TypeScript exact types [OK]
Common Mistakes:
Thinking it speeds up runtime
Believing it allows dynamic type changes
Assuming it removes need for type annotations
2. Which of the following is a correct way to narrow a variable's type in TypeScript?
easy
A. function test(value: number | string) { return value; }
B. value = 'string' as number;
C. let value: any = 5; value = 'hello';
D. if (typeof value === 'string') { /* value is string here */ }
Solution
Step 1: Identify type narrowing syntax
Using typeof checks like typeof value === 'string' narrows the type inside the block.
Step 2: Check other options for correctness
value = 'string' as number; forces wrong type with as, let value: any = 5; value = 'hello'; uses any without narrowing, function test(value: number | string) { return value; } does not narrow inside function.
Final Answer:
if (typeof value === 'string') { /* value is string here */ } -> Option D
Quick Check:
typeof check narrows type [OK]
Hint: Use typeof or instanceof to narrow types [OK]
Common Mistakes:
Using 'as' to force wrong types
Not using any type checks
Confusing type assertion with narrowing
3. What will be the output of this TypeScript code?
function printLength(x: string | number) {
if (typeof x === 'string') {
return x.length;
} else {
return x.toFixed(2);
}
}
console.log(printLength('hello'));
console.log(printLength(3.14159));
medium
A. hello and 3.14
B. 5 and 3.14159
C. 5 and 3.14
D. Error because length is not on number
Solution
Step 1: Analyze the type narrowing in the function
The if checks if x is a string, then returns its length (5 for 'hello'). Else, it treats x as number and calls toFixed(2).
Step 2: Evaluate the outputs for given inputs
For 'hello', output is 5. For 3.14159, toFixed(2) returns '3.14'.
Final Answer:
5 and 3.14 -> Option C
Quick Check:
Type narrowing enables correct method calls [OK]
Hint: Check typeof to know which method runs [OK]
Common Mistakes:
Expecting full decimal for number output
Assuming length works on number
Ignoring type narrowing effect
4. Identify the error in this TypeScript code and why type narrowing is needed:
function process(value: string | number) {
console.log(value.length);
}
medium
A. Error: string type cannot be logged
B. Error: number type has no 'length' property, need narrowing
C. No error, code runs fine
D. Error: function missing return type
Solution
Step 1: Understand the union type usage
The parameter value can be string or number, but length exists only on string.
Step 2: Identify why narrowing is needed
Without checking type, accessing length on number causes error. Type narrowing is needed to safely access length.
Final Answer:
Error: number type has no 'length' property, need narrowing -> Option B
Quick Check:
Accessing properties needs type narrowing [OK]
Hint: Check type before accessing properties [OK]
Common Mistakes:
Ignoring union types
Assuming all types have same properties
Not using if or typeof checks
5. You have a function that accepts string | number | null. You want to safely return the string length or number fixed to 1 decimal, or 0 if null. Which code correctly uses type narrowing?
hard
A. function format(x: string | number | null) {
if (x === null) return 0;
if (typeof x === 'string') return x.length;
return x.toFixed(1);
}
B. function format(x: string | number | null) {
if (x) return x.length || x.toFixed(1);
return 0;
}
C. function format(x: string | number | null) {
return x.length ?? x.toFixed(1) ?? 0;
}
D. function format(x: string | number | null) {
if (typeof x === 'number') return x.length;
else if (typeof x === 'string') return x.toFixed(1);
else return 0;
}
Solution
Step 1: Check handling of null
function format(x: string | number | null) {
if (x === null) return 0;
if (typeof x === 'string') return x.length;
return x.toFixed(1);
} explicitly returns 0 if x is null, which is correct.
Step 2: Verify type narrowing for string and number
function format(x: string | number | null) {
if (x === null) return 0;
if (typeof x === 'string') return x.length;
return x.toFixed(1);
} uses typeof to check string and number separately, calling correct methods safely.
Step 3: Identify errors in other options
function format(x: string | number | null) {
if (x) return x.length || x.toFixed(1);
return 0;
} incorrectly uses x.length || x.toFixed(1) without narrowing; function format(x: string | number | null) {
return x.length ?? x.toFixed(1) ?? 0;
} uses nullish coalescing incorrectly; function format(x: string | number | null) {
if (typeof x === 'number') return x.length;
else if (typeof x === 'string') return x.toFixed(1);
else return 0;
} swaps methods for types.
Final Answer:
function format(x: string | number | null) {
if (x === null) return 0;
if (typeof x === 'string') return x.length;
return x.toFixed(1);
} -> Option A
Quick Check:
Explicit checks safely narrow types [OK]
Hint: Check null first, then typeof string or number [OK]
Common Mistakes:
Not checking null before accessing properties
Mixing up string and number methods
Using || or ?? without narrowing
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.