0
0
Typescriptprogramming~5 mins

Equality narrowing in Typescript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is equality narrowing in TypeScript?
Equality narrowing is a feature where TypeScript uses equality checks (like === or !==) to narrow down the possible types of a variable within a code block.
Click to reveal answer
beginner
How does TypeScript narrow types after an if (x === null) check?
Inside the if block, TypeScript knows x is exactly null. Outside, it knows x is not null and narrows the type accordingly.
Click to reveal answer
beginner
Given <code>let value: string | number;</code> what happens after <code>if (typeof value === 'string')</code>?
Inside the if block, TypeScript narrows value to string. Outside, it narrows value to number.
Click to reveal answer
intermediate
Can equality narrowing work with custom types or only primitives?
Equality narrowing works with any types where equality checks make sense, including primitives like string, number, null, and also with literal types and enums.
Click to reveal answer
intermediate
What happens if you compare two variables of union types with === in TypeScript?
TypeScript narrows the types of both variables to the overlapping types that can be equal, helping catch impossible comparisons or refine types inside the check.
Click to reveal answer
What does TypeScript do after if (x === null)?
ANarrows <code>x</code> to <code>undefined</code> inside the block
BNarrows <code>x</code> to <code>null</code> inside the block
CNarrows <code>x</code> to <code>string</code> inside the block
DDoes not narrow <code>x</code>
Given let val: string | number; what is val inside if (typeof val === 'string')?
Astring
Bboolean
Cstring | number
Dnumber
Does equality narrowing work with enum types in TypeScript?
AOnly with numeric enums
BNo, enums are not narrowed
COnly with string enums
DYes, it narrows based on enum values
What happens if you compare two union type variables with ===?
ATypeScript narrows both to overlapping types
BTypeScript throws an error
CTypeScript ignores the check
DTypeScript widens the types
Which operator triggers equality narrowing in TypeScript?
A+
B-
C===
D*
Explain how equality narrowing helps TypeScript understand variable types inside an if statement.
Think about how checking if a variable equals a value changes what TypeScript knows about it.
You got /4 concepts.
    Describe what happens when you compare two union type variables with === in TypeScript.
    Consider how TypeScript finds common types that can be equal.
    You got /3 concepts.