TypeScript if-else Conditional Statement
A TypeScript if-else statement selects one of two execution paths. The if block runs when its condition is truthy. If the condition is falsy, the optional else block runs instead.
Use if when code should run only under a particular condition. Add else when an alternative action is required, or use an else if chain when several mutually exclusive conditions must be tested.
TypeScript if-else Syntax
The syntax of a TypeScript if-else statement is:
if(expression) {
/* if block statements */
} else {
/* else block statements */
}
expressionis evaluated before either block runs.- The
ifblock runs when the expression is truthy. - The
elseblock runs when the expression is falsy. - Braces make the boundaries of each branch clear and help prevent errors when more statements are added later.
Although a Boolean expression is usually the clearest condition, TypeScript follows JavaScript truthiness rules. Values such as false, 0, an empty string, null, undefined, and NaN are falsy. Objects and arrays, including empty ones, are truthy.
TypeScript if-else Example
The following TypeScript example evaluates equality and comparison conditions.
example.ts
var a:number = 1
var b:number = 3
if(a == 1){
console.log("value of a is 1.")
} else {
console.log("value of a is not 1.")
}
if(a == b){
console.log("a and b are equal.")
} else {
console.log("a and b are not equal.")
}
When the code is compiled with tsc example.ts, the TypeScript compiler generates the following JavaScript.
example.js
var a = 1;
var b = 3;
if (a == 1) {
console.log("value of a is 1.");
}
else {
console.log("value of a is not 1.");
}
if (a == b) {
console.log("a and b are equal.");
}
else {
console.log("a and b are not equal.");
}
The branching syntax is the same in TypeScript and JavaScript. Type annotations are removed during compilation, while the runtime condition remains JavaScript.
For new code, prefer the strict equality operators === and !==. They compare values without applying the type coercion performed by == and !=.
const itemCount: number = 3;
if (itemCount === 3) {
console.log("There are exactly three items.");
} else {
console.log("The item count is not three.");
}
TypeScript else-if Ladder for Multiple Conditions
An else if ladder tests several conditions in order. Evaluation stops at the first truthy condition, so only one matching branch runs. An optional final else can handle every value not matched earlier.
example.ts
var a:number = 1
var b:number = 3
if(a == b){
console.log("a and b are equal.")
} else if (a>b) {
console.log("a is greater than b.")
} else if (a<b) {
console.log("a is less than b.")
}
Because the values are 1 and 3, the final else if condition is true and the program reports that a is less than b.
Order the branches from the most specific condition to the most general. For example, a score of 92 satisfies both score >= 90 and score >= 60, so the higher threshold must be tested first.
const score: number = 76;
let result: string;
if (score >= 90) {
result = "Distinction";
} else if (score >= 60) {
result = "Pass";
} else {
result = "Needs improvement";
}
console.log(result);
Pass
Combining TypeScript Conditions with AND, OR, and NOT
Logical operators let an if statement evaluate related requirements together. Use && when every condition must be true, || when at least one condition must be true, and ! to negate a Boolean value.
const age: number = 24;
const hasAccessCard: boolean = true;
if (age >= 18 && hasAccessCard) {
console.log("Access granted");
} else {
console.log("Access denied");
}
The && and || operators short-circuit. With &&, the second operand is not evaluated if the first is falsy. With ||, the second operand is not evaluated if the first is truthy.
TypeScript if Statement for Type Narrowing
TypeScript also uses conditional checks to narrow union types. After a typeof check, the compiler can treat the value as the identified type inside that branch.
function formatReference(reference: string | number): string {
if (typeof reference === "number") {
return reference.toFixed(0);
} else {
return reference.trim().toUpperCase();
}
}
console.log(formatReference(" ab-42 "));
console.log(formatReference(105.7));
AB-42
106
Inside the first branch, reference is a number. Inside the else branch, it is a string. This allows type-specific methods without assertions.
One-Line TypeScript if-else with the Ternary Operator
For a short conditional value assignment, TypeScript supports the ternary operator. Its form is condition ? valueWhenTrue : valueWhenFalse.
const temperature: number = 31;
const message: string = temperature > 30 ? "Hot" : "Moderate";
console.log(message);
The ternary operator is an expression and produces a value. An if-else construct is a statement and controls which statements execute. Use a regular if-else when a branch contains several operations or when nested ternary expressions would reduce readability.
Nested TypeScript if-else Statements
An if or else block may contain another conditional statement. This is useful when the second decision is relevant only after the first condition succeeds.
const isSignedIn: boolean = true;
const role: string = "editor";
if (isSignedIn) {
if (role === "admin") {
console.log("Open admin dashboard");
} else {
console.log("Open user dashboard");
}
} else {
console.log("Show sign-in page");
}
Deeply nested conditions can be difficult to follow. Functions, early returns, or clearly named Boolean variables can often express the same rules more directly.
Common TypeScript if-else Mistakes
- Using assignment as a condition:
if (status = "ready")assigns a value. Useif (status === "ready")to compare values. - Testing broader conditions first: In an
else ifladder, an early general condition can make a later specific branch unreachable. - Confusing an empty array with a falsy value:
[]is truthy. Testitems.length === 0when checking whether an array is empty. - Using a truthiness check when zero is valid:
if (quantity)rejects zero. Compare explicitly when zero has a distinct meaning. - Omitting braces: A brace-free branch controls only the next statement and can behave unexpectedly after another statement is added.
TypeScript if-else Frequently Asked Questions
Does a TypeScript if condition have to be Boolean?
No. Conditions follow JavaScript truthiness rules, although an explicit Boolean expression is often easier to understand and type-check. Falsy values include false, 0, "", null, undefined, and NaN.
How do I write TypeScript if-else on one line?
Use the ternary operator for a simple conditional value: const label = active ? "Active" : "Inactive";. Keep a normal if-else statement when either branch performs multiple actions.
What is the difference between == and === in a TypeScript condition?
The == operator may convert operand types before comparison. The === operator requires both the type and value to match. Strict equality is generally the more predictable choice.
Can TypeScript narrow a type inside an if statement?
Yes. Checks such as typeof, instanceof, property-presence tests, and discriminated-union comparisons can narrow a value to a more specific type within a branch.
Does TypeScript if-else behave differently in a web page?
No. TypeScript is compiled to JavaScript, and the generated JavaScript performs the runtime branching. In a browser application, the branch can call functions or update the DOM, but TypeScript code is not placed directly in HTML for the browser to execute.
TypeScript if-else Editorial QA Checklist
- Confirm that each example places the most specific
else ifcondition before broader conditions. - Check that new comparisons use
===or!==unless coercion is intentionally demonstrated. - Verify that truthy and falsy behavior is not described as strict Boolean-only evaluation.
- Compile the TypeScript examples and compare their console output with the displayed result blocks.
- Confirm that type-narrowing examples use methods valid for the narrowed type in each branch.
TypeScript if-else Summary
A TypeScript if statement runs a branch when its condition is truthy, while else supplies the alternative branch. Use else if for ordered multiple-choice logic, logical operators for combined conditions, and the ternary operator for short conditional values. Type checks inside these statements can also narrow union types. Continue with the main TypeScript Tutorial for related language features.
TutorialKart.com