TypeScript if Conditional Statement
A TypeScript if statement executes a block of code when its condition evaluates to a truthy value. It is used to make runtime decisions based on variables, comparisons, function results, and other expressions.
If the condition is truthy, the statements inside the braces run. If it is falsy, TypeScript skips that block and continues with the next statement. TypeScript uses the same runtime conditional behavior as JavaScript, while its type checker can also narrow variable types inside a validated branch.
TypeScript if Statement Syntax
Following is the syntax of TypeScript if statement :
if(expression) {
/* block of statements */
}
- expression should return a boolean value.
- block of statements enclosed between curly braces are executed only if the expression evaluates to true.
In ordinary TypeScript code, use braces even when the branch contains only one statement. Braces make the branch boundary clear and reduce errors when more statements are added later.
TypeScript if Statement Example
Following is an example TypeScript code to demonstrate if conditional statement.
ifExample.ts
var a:number = 1
var b:number = 3
if(a == 1){
console.log("value of a is 1.")
}
if(a == b){
console.log("a and b are equal.")
}
When the above code is compiled using typescript compiler, tsc ifExample.ts , following JavaScript code is generated.
ifExample.js
var a = 1;
var b = 3;
if (a == 1) {
console.log("value of a is 1.");
}
if (a == b) {
console.log("a and b are equal.");
}
The first condition is true, so its message is printed. The second condition is false because a and b contain different numbers. There is no visible difference between the TypeScript and generated JavaScript conditional blocks because type annotations are removed during compilation.
The original example uses the loose equality operator ==. New TypeScript code normally uses strict equality, ===, to avoid JavaScript type coercion during a comparison.
const itemCount: number = 3;
if (itemCount === 3) {
console.log("There are three items.");
}
Boolean Conditions in a TypeScript if Statement
A condition can be a Boolean variable, a comparison, a logical expression, or a function call that returns a Boolean value. Common comparison operators include ===, !==, >, <, >=, and <=.
const age: number = 22;
const hasPermission: boolean = true;
if (age >= 18 && hasPermission) {
console.log("Access allowed.");
}
The logical AND operator && requires both expressions to be truthy. The logical OR operator || succeeds when at least one expression is truthy, while ! negates a condition.
Truthy and Falsy Values in TypeScript if Conditions
Although an explicit Boolean condition is often easiest to read, JavaScript runtime rules allow other values in an if condition. Values such as false, 0, NaN, an empty string, null, and undefined are falsy. Most other values, including empty arrays and empty objects, are truthy.
const username: string = "Ravi";
if (username) {
console.log(`Signed in as ${username}`);
}
This branch runs because username contains a non-empty string. When values such as 0 or an empty string are valid application data, use an explicit comparison rather than relying on truthiness.
TypeScript if Statement with String Conditions
Use strict equality to test whether a string matches an expected value. String comparisons are case-sensitive, so normalize user input when uppercase and lowercase variants should be treated alike.
const status: string = "active";
if (status === "active") {
console.log("The account is active.");
}
const answer: string = "YES";
if (answer.trim().toLowerCase() === "yes") {
console.log("The user confirmed.");
}
Use includes(), startsWith(), or another string method when the requirement is to inspect part of a string rather than match the complete value.
TypeScript if Statement for Type Narrowing
TypeScript analyzes conditions to determine a more specific type inside a branch. This process is called type narrowing. It is useful when a parameter can contain more than one type.
function formatReference(reference: string | number): string {
if (typeof reference === "number") {
return reference.toFixed(0);
}
return reference.trim().toUpperCase();
}
Inside the if block, TypeScript knows that reference is a number. After that branch returns, the remaining value is known to be a string. Other narrowing checks include instanceof, the in operator, equality checks, and user-defined type guards.
Checking null and undefined with TypeScript if
When strict null checking is enabled, test an optional value before using methods or properties that require a defined value.
function printName(name: string | null | undefined): void {
if (name !== null && name !== undefined) {
console.log(name.toUpperCase());
}
}
The concise condition name != null also excludes both null and undefined, but explicit strict comparisons can make the intended checks clearer. A simple if (name) additionally excludes an empty string, which may not match the application’s requirement.
TypeScript if, else if, and else Branches
Add else if when several mutually exclusive conditions must be tested in order. Add else for the fallback branch. Evaluation stops after the first matching branch.
const score: number = 72;
if (score >= 90) {
console.log("Grade A");
} else if (score >= 75) {
console.log("Grade B");
} else if (score >= 60) {
console.log("Grade C");
} else {
console.log("Grade D");
}
Order matters in a chain of numeric ranges. Test the most restrictive upper threshold first; otherwise, a broader condition may match before the intended branch is reached.
One-Line TypeScript Condition with the Ternary Operator
The conditional or ternary operator selects one of two expressions and is sometimes described as a shorthand if...else. Its syntax is condition ? valueWhenTrue : valueWhenFalse.
const temperature: number = 31;
const label: string = temperature >= 30 ? "Hot" : "Moderate";
console.log(label);
Use a ternary expression for a short value selection. Prefer a regular if...else statement when branches contain several operations or when nested ternaries would make the logic difficult to read.
Using TypeScript if Logic with HTML
An if statement belongs in TypeScript code, not directly in static HTML markup. A TypeScript program can evaluate a condition and then update an HTML element through the DOM. Framework templates may provide their own conditional rendering syntax, which is separate from a TypeScript if statement.
const messageElement = document.querySelector<HTMLElement>("#message");
const isLoggedIn: boolean = true;
if (messageElement && isLoggedIn) {
messageElement.textContent = "Welcome back.";
}
The first part of the condition checks that the element exists. This narrows messageElement from HTMLElement | null to HTMLElement before its textContent property is used.
TypeScript if Statements and Conditional Types Are Different
A TypeScript if statement controls which code runs at runtime. A conditional type operates only in the type system and selects a type using syntax that resembles the ternary operator. Conditional types do not create runtime branches.
type Result<T> = T extends string ? "text" : "other";
type StringResult = Result<string>; // "text"
type NumberResult = Result<number>; // "other"
Use an if statement to inspect actual runtime values. Use a conditional type when a compile-time type must depend on another type.
Common TypeScript if Statement Mistakes
- Using assignment instead of comparison: Write
value === 10, notvalue = 10, when testing equality. - Depending on loose equality: Prefer
===and!==so that operands are not coerced to different types. - Confusing falsy data with missing data: A condition such as
if (count)rejects the valid number0. Compare explicitly when zero is allowed. - Placing broad conditions first: In an
else ifchain, an earlier match prevents later conditions from being evaluated. - Confusing runtime conditions with conditional types: Conditional types affect type checking, while
ifstatements affect program execution. - Writing an empty object check as
if (object): Empty objects are truthy. Inspect the required properties or useObject.keys(object).lengthwhen emptiness is relevant.
TypeScript if Statement FAQs
Does a TypeScript if condition have to return a Boolean?
A Boolean expression is the clearest choice, but runtime conditions can contain other values. JavaScript truthiness rules determine whether those values take the true or false branch.
How do I write a one-line if statement in TypeScript?
Use the ternary operator when selecting between two short expressions, such as const label = valid ? "Yes" : "No";. A regular braced if statement is clearer for multi-step branches.
How do I compare strings in a TypeScript if condition?
Use strict equality, as in status === "active". String comparison is case-sensitive, so apply methods such as trim() and toLowerCase() first when normalized input is required.
How do I check a variable’s type in a TypeScript if statement?
Use typeof for primitive values, instanceof for class instances, or the in operator for distinguishing object shapes. TypeScript uses these checks to narrow the variable inside the branch.
Can I place a TypeScript if statement directly in HTML?
No. Static HTML does not support TypeScript statements. Run the condition in TypeScript and modify the DOM, or use the conditional template syntax supplied by the selected web framework.
TypeScript if Statement Editorial QA Checklist
- Confirm that each
ifexample compiles as TypeScript and demonstrates a reachable branch. - Verify that equality examples use
===unless type coercion is intentionally being explained. - Check that truthy and falsy examples account for valid values such as
0and an empty string. - Ensure that type-narrowing examples show the variable’s more specific type inside the validated branch.
- Keep runtime
ifstatements clearly separated from compile-time conditional types.
TypeScript if Conditional Statement Summary
In this TypeScript Tutorial, we have learnt about the if conditional statement, Boolean and truthy conditions, strict string and number comparisons, null checks, type narrowing, else if branches, and the ternary operator. A TypeScript if statement follows JavaScript runtime behavior while also helping the compiler narrow types within validated branches.
TutorialKart.com