TypeScript — If Statement: Build Reliable Conditional Logic with Type Safety
Introduction – Understanding the if Statement in TypeScript
The if statement is a foundational tool used to make decisions in your code. In TypeScript, it works just like in JavaScript but comes with an added advantage: type narrowing. This means TypeScript can smartly determine a variable’s type depending on conditions, helping you write more reliable and type-safe logic.
This article will teach you how to:
- Use basic
if,else, andelse ifstructures - Leverage type narrowing in conditional blocks
- Apply
ifstatements with union types and guards - Avoid common mistakes in conditional logic
Basic Structure of an if Statement
The if statement evaluates a condition. If it’s true, it runs a block of code. You can also add else or else if for additional conditions.
let temperature = 30;
if (temperature > 25) {
console.log("It's warm outside.");
} else if (temperature < 10) {
console.log("It's cold outside.");
} else {
console.log("The weather is moderate.");
}
This checks the temperature and prints a message accordingly.
Type Narrowing with if Conditions
One of TypeScript’s superpowers is its ability to refine types based on conditional checks.
Example:
function display(value: number | string) {
if (typeof value === "string") {
console.log("String length:", value.length); // Type narrowed to string
} else {
console.log("Number:", value.toFixed(2)); // Type narrowed to number
}
}
Explanation: TypeScript detects the condition and narrows the type inside each block automatically.
Checking Truthy and Falsy Values
Some values like false, 0, "", null, undefined, and NaN are considered falsy. Everything else is truthy.
Example:
function sayHello(name?: string) {
if (name) {
console.log(`Hello, ${name}`);
} else {
console.log("Hello, guest");
}
}
If no name is provided, it defaults to greeting a guest.
Combining Conditions with Logical Operators
You can use && (AND) and || (OR) for compound conditions.
Logical AND:
if (user && user.isVerified) {
console.log("Welcome back!");
}
Logical OR:
if (role === "admin" || role === "moderator") {
console.log("Access granted");
}
Nested if Statements
You can write one if inside another, but keep it readable.
if (account) {
if (account.balance > 0) {
console.log("You have available funds.");
}
}
Tip: Use early returns or combine conditions to avoid deep nesting.
Real-World Applications
- Validating user input:
if (input.length === 0) - Role-based access:
if (user.role === "admin") - API response checks:
if (response.status === 200) - Conditional rendering in UI components
- Safe object access with type checks
Common Mistakes and Fixes
| Mistake | Solution |
|---|---|
Using = instead of === | Use strict equality: === for value + type checks |
| Over-nesting conditions | Use guard clauses or combine conditions |
| Not handling all scenarios | Include else to handle default cases |
| Ignoring union type logic | Use type guards like typeof or instanceof |
Best Practices
- Use
===and!==for strict equality - Narrow types using
typeof,instanceof, orin - Handle all code paths—don’t skip default cases
- Keep conditions short and readable
- Use optional chaining or truthy checks when accessing deep properties
Summary – Key Takeaways
The if statement in TypeScript offers both simple decision-making and advanced type-safe branching. It lets you write conditional logic that’s not only functional but also protected by the compiler.
Recap:
if,else if, andelseguide the program flow based on conditions- TypeScript narrows types within conditional blocks automatically
- Use logical operators to combine multiple checks
- Always write clear and complete condition handling
In action: Whether you’re building a UI or validating API responses, TypeScript’s if statement is your go-to tool for reliable logic.
FAQs – TypeScript If Statement
Does TypeScript enhance the if statement compared to JavaScript?
Yes. It performs type narrowing based on your conditions.
What is type narrowing?
It’s the ability to refine variable types based on logic—like checking typeof.
Should I use == or ===?
Use === for both type and value checks. It’s more predictable.
Can I combine multiple conditions in one if?
Yes, using && and ||.
Does if (variable) check for null and undefined?
Yes. Falsy checks cover both null and undefined.
Share Now :
