TypeScript Reference ยท Keywords and Declarations
TypeScript if and else
Reference for if, else if and else in TypeScript: truthiness, how conditions narrow union types, early returns, the ternary operator and common narrowing pitfalls.
if runs a block when its condition is truthy, and else runs another block otherwise. In TypeScript the condition does more than choose a branch: it narrows types. Inside the if block the compiler treats a variable as the more specific type that the test proves, and in the else block as whatever remains.
This is called control-flow narrowing and it works with typeof, instanceof, in, equality, truthiness, discriminant properties and your own type guards.
function len(x: string | string[]) { if (typeof x === "string") { return x.length; // x: string } return x.length; // x: string[] }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
if (condition) { // ... } else if (other) { // ... } else { // ... } const result = condition ? a : b; // conditional expression, narrows too
| Part | Description |
|---|---|
condition |
Any expression. It is converted to a boolean by JavaScript truthiness rules. |
else if |
Another test, evaluated only if the previous ones were falsy. |
else |
The fallback block. |
Falsy values are false, 0, -0, 0n, "", null, undefined and NaN; everything else is truthy, including "0", [] and {}.
Errors and edge cases:
- A condition that is always true or false can be flagged: for example, testing a function without calling it in an
ifis error TS2774 ("This condition will always return true since this function is always defined. Did you mean to call it instead?"). - Comparing types with no overlap, such as
if (x === "a")whenx: number, is error TS2367 ("This comparison appears to be unintentional because the types 'number' and 'string' have no overlap"). - Using
ifafter exhausting a union leavesneverin the finalelse, which you can use for exhaustiveness checks.
Usage notes
- Prefer early returns. An
if (bad) return;followed by the main code narrows the rest of the function without nesting. - Truthiness is blunt.
if (value)narrows awaynullandundefined, but also0,""andNaN. Compare explicitly when those are valid. - Narrowing through aliases. Since TypeScript 4.4, a condition stored in a
const(const isStr = typeof x === "string") still narrowsxwhen used inif (isStr). - Narrowing is reset by assignments and, for
letor properties, by function calls in some cases. Copy to aconstwhen you need stability. - No block, no scope. Always use braces; a missing brace is a classic source of bugs, and the dangling
elsepairs with the nearestif. - Ternary (
a ? b : c) narrows the same way, and the result type is the union of the two branches. - Optional chaining and
??replace manyif (x != null)checks. See the narrowing lesson.
Related
- switch, typeof (value), instanceof, in
- Lessons: Narrowing, Discriminated unions, Custom type guards