TypeScript If-Else Conditional Logic

Recently, I was working on a project where I needed to implement complex conditional logic in TypeScript. After years of using JavaScript, I’ve found that TypeScript’s type system makes if-else statements much more powerful and reliable.

In this blog, I’ll explain different ways to use TypeScript’s if-else conditional logic, along with practical examples that go beyond the basic syntax.

Basic If-Else Statement in TypeScript

The most fundamental form of conditional logic in TypeScript is the if-else statement. It works just like in JavaScript, but with the added benefit of TypeScript’s type checking.

function checkVotingEligibility(age: number): string {
  if (age >= 18) {
    return "You are eligible to vote in the US.";
  } else {
    return "You are not eligible to vote yet.";
  }
}

console.log(checkVotingEligibility(20)); // "You are eligible to vote in the US."
console.log(checkVotingEligibility(16)); // "You are not eligible to vote yet."

Output:

If else conditionals in TypeScript

The TypeScript compiler ensures that the age parameter is always a number, providing type safety that vanilla JavaScript doesn’t offer.

Check out: Nullish Coalescing (??) vs Logical OR (||) Operator in TypeScript

If-Else-If Statement for Multiple Conditions

When you need to check multiple conditions, you can use the if-else-if ladder:

function getTaxBracket(income: number): string {
  if (income < 10275) {
    return "10% tax bracket";
  } else if (income < 41775) {
    return "12% tax bracket";
  } else if (income < 89075) {
    return "22% tax bracket";
  } else if (income < 170050) {
    return "24% tax bracket";
  } else {
    return "Higher tax bracket";
  }
}

console.log(getTaxBracket(50000)); // "22% tax bracket"

Output:

If else with multiple conditions in TypeScript

This example uses 2025 US federal tax brackets for a single filer to determine which bracket someone falls into based on their income.

Using TypeScript Type Guards with If-Else

One of TypeScript’s most powerful features is its ability to narrow types within conditional blocks. This is called type guarding:

function processValue(value: string | number): string {
  if (typeof value === "string") {
    // TypeScript knows value is a string here
    return value.toUpperCase();
  } else {
    // TypeScript knows value is a number here
    return `The number is: ${value.toFixed(2)}`;
  }
}

console.log(processValue("hello")); // "HELLO"
console.log(processValue(42.123)); // "The number is: 42.12"

Output:

TypeScript Type Guards with If-Else

The typeof check acts as a type guard, allowing TypeScript to know the exact type within each branch of the if-else statement.

Check out: Double Question Mark (??) Operator in TypeScript

Conditional (Ternary) Operator

For simple conditions, the ternary operator provides a concise alternative to if-else:

function getShippingCost(state: string, orderTotal: number): number {
  return state === "NY" || state === "CA" ? orderTotal * 0.08 : orderTotal * 0.05;
}

console.log(getShippingCost("NY", 100)); // 8
console.log(getShippingCost("TX", 100)); // 5

Output:

Conditional Ternary Operator in TypeScript

This example calculates shipping costs based on the state, with higher rates for New York and California.

Using If-Else with TypeScript Interfaces and Type Narrowing

TypeScript’s type system really shines when working with custom types and interfaces:

interface Cash {
  type: "cash";
  amount: number;
}

interface CreditCard {
  type: "credit";
  cardNumber: string;
  expiryDate: string;
}

type PaymentMethod = Cash | CreditCard;

function processPayment(payment: PaymentMethod): string {
  if (payment.type === "cash") {
    // TypeScript knows payment is Cash here
    return `Processing cash payment of $${payment.amount}`;
  } else {
    // TypeScript knows payment is CreditCard here
    return `Processing credit card ${payment.cardNumber} expiring ${payment.expiryDate}`;
  }
}

const cashPayment: Cash = { type: "cash", amount: 99.99 };
const cardPayment: CreditCard = { 
  type: "credit", 
  cardNumber: "4111-1111-1111-1111", 
  expiryDate: "01/25" 
};

console.log(processPayment(cashPayment)); 
// "Processing cash payment of $99.99"

console.log(processPayment(cardPayment)); 
// "Processing credit card 4111-1111-1111-1111 expiring 01/25"

Output:

If-Else with TypeScript Interfaces

The discriminated union pattern with the type property allows TypeScript to automatically narrow the type in each branch.

Check out: TypeScript Interface Function Properties

Nullish Coalescing and Optional Chaining with If-Else

TypeScript supports modern JavaScript features that can simplify conditional logic:

interface User {
  id: number;
  name: string;
  address?: {
    street: string;
    city: string;
    state: string;
  };
}

function getUserState(user: User): string {
  // Using optional chaining and nullish coalescing
  const state = user.address?.state ?? "No state provided";

  // This is equivalent to:
  /*
  let state: string;
  if (user.address && user.address.state) {
    state = user.address.state;
  } else {
    state = "No state provided";
  }
  */

  return state;
}

const user1: User = {
  id: 1,
  name: "John Doe",
  address: {
    street: "123 Main St",
    city: "Boston",
    state: "MA"
  }
};

const user2: User = {
  id: 2,
  name: "Jane Smith"
};

console.log(getUserState(user1)); // "MA"
console.log(getUserState(user2)); // "No state provided"

Output:

Optional Chaining with If Else in TypeScript

Optional chaining (?.) and nullish coalescing (??) can replace many if-else statements, making your code cleaner and more readable.

Check out: Conditionally Add Property to Object in TypeScript

Switch Statement as an Alternative to If-Else

For multiple conditions checking against a single value, a switch statement can be clearer:

function getStateTaxRate(state: string): number {
  switch (state.toUpperCase()) {
    case "CA":
      return 0.0725; // California
    case "NY":
      return 0.045; // New York
    case "TX":
      return 0.0625; // Texas
    case "FL":
      return 0.06; // Florida
    default:
      return 0.05; // Default rate
  }
}

console.log(getStateTaxRate("CA")); // 0.0725
console.log(getStateTaxRate("OH")); // 0.05

Output:

if else alternative in TypeScript

The switch statement can be more readable when you have many conditions against a single value.

Typescript If-Else Best Practices

After years of working with TypeScript, I’ve developed some best practices for conditional logic:

  1. Use type guards: Let TypeScript narrow types for you in conditional branches.
  2. Keep conditions simple: Complex conditions are harder to read and maintain.
  3. Consider alternatives: Ternary operators, nullish coalescing, and optional chaining can often replace if-else statements.
  4. Use early returns: For functions with multiple exit points, early returns can make code clearer.
// Example of early returns
function getUserAccessLevel(user: User | null): string {
  if (!user) return "No access";
  if (user.isAdmin) return "Admin access";
  if (user.isPremium) return "Premium access";
  return "Basic access";
}

TypeScript’s type system makes if-else statements more powerful than they are in JavaScript. With proper type guards, the compiler can help catch errors that would otherwise only surface at runtime.

Conclusion

In this TypeScript tutorial, we have learned how to write conditional logic using if-else, if-else-if, and switch statements. We also learned about JavaScript features such as optional chaining (?.) and nullish coalescing (??) that simplify conditional expressions.

By following the above example, you will be able to use the if-else conditionals to define the conditions in your TypeScript code.

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.