Ternary Operator in TypeScript

Recently, I was working on a TypeScript project for a financial services company where we needed to simplify our codebase. One feature I found incredibly useful was the ternary operator, which helped us reduce complex if-else statements into clean, single-line expressions.

In this article, I’ll show you how to effectively use the ternary operator in TypeScript to write code in a simplified way.

What is the Ternary Operator?

The ternary operator (also called the conditional operator) is a shorthand way to write an if-else statement in a single line. It’s called “ternary” because it takes three operands:

  1. A condition to evaluate
  2. An expression to execute if the condition is true
  3. An expression to execute if the condition is false

The syntax looks like this:

condition ? expressionIfTrue : expressionIfFalse

Basic Usage of the Ternary Operator

Let’s start with a simple example that you might use in a US e-commerce application:

const isHolidaySeason = true;

// Instead of writing this:
let discount: number;
if (isHolidaySeason) {
  discount = 0.2; // 20% holiday discount
} else {
  discount = 0.05; // 5% regular discount
}
console.log("Traditional if-else discount:", discount);

// You can write this:
const ternaryDiscount: number = isHolidaySeason ? 0.2 : 0.05;
console.log("Ternary discount:", ternaryDiscount);

Output:

Ternary Operator in TypeScript

The ternary version is much cleaner and easier to read. It also allows you to declare and initialize a variable in a single statement.

Check out: Create an Object from an Interface in TypeScript

Using Ternary Operators with TypeScript Types

One of the powerful features of TypeScript is its type system, and the ternary operator works seamlessly with it:

// Define union type
type PaymentMethod = 'creditCard' | 'paypal' | 'bankTransfer';

// Use ternary with type checking
const processingFee: number = 
  (paymentMethod === 'creditCard') ? 2.9 :
  (paymentMethod === 'paypal') ? 3.4 : 1.5;

TypeScript will correctly infer the return type from the ternary expression, which helps catch errors during development.

Chaining Ternary Operators

You can chain ternary operators to handle multiple conditions, similar to if-else-if statements:

const totalSpent: number = 720;

// User status based on purchase history
const userStatus: string = 
  totalSpent > 1000 ? "Gold" :
  totalSpent > 500 ? "Silver" :
  totalSpent > 100 ? "Bronze" : 
  "Standard";

console.log('Total Spent: $${totalSpent}');
console.log('User Status: ${userStatus}');

Output:

TypeScript Ternary Operator

This approach is concise but can become hard to read with too many conditions. I generally limit it to 3-4 conditions before considering a different approach.

Ternary Operators in JSX (React with TypeScript)

If you’re using TypeScript with React, the ternary operator is incredibly useful for conditional rendering:

// Rendering a component based on user authentication status
return (
  <div>
    {isAuthenticated 
      ? <UserDashboard userData={userData} /> 
      : <LoginPrompt redirectUrl="/dashboard" />}
  </div>
);

This is much cleaner than using separate if statements or additional variables to determine what to render.

Check out:

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

Using Ternary with Template Literals

Template literals combined with ternary operators create powerful string formatting capabilities:

// Sample input values
const isExpressShipping: boolean = true;
const requiresSignature: boolean = false;
const address = {
  zipCode: "94107"
};

// Format a shipping status message using ternary operators
const shippingMessage: string = `Your order will arrive ${
  isExpressShipping ? 'tomorrow' : 'in 3-5 business days'
} to ${address.zipCode}. ${
  requiresSignature ? 'Signature will be required upon delivery.' : ''
}`;

console.log(shippingMessage);

Output:

Ternary Operators with literals in TypeScript

Handling Null and Undefined with Ternary

The ternary operator is perfect for providing fallback values when dealing with potentially null or undefined data:

// Sample user object (you can change name to undefined to test fallback)
const user: { name?: string } = { name: undefined };

// Get user's display name with fallback (using ternary operator)
const displayNameTernary: string = user?.name ? user.name : 'Guest User';
console.log("Display Name (Ternary):", displayNameTernary);

// Get user's display name with fallback (using nullish coalescing)
const displayNameNullish: string = user?.name ?? 'Guest User';
console.log("Display Name (Nullish Coalescing):", displayNameNullish);

Output:

Ternary Operator with null coalesce in TypeScript

Check out: Conditionally Add Property to Object in TypeScript

Advanced Pattern: Ternary with Destructuring

Here’s a pattern I’ve found useful when working with complex objects:

// Sample user state
const userState: string = 'DE';

// Different tax calculations based on state using chained ternary
const { taxRate, taxExempt } =
  userState === 'NY' ? { taxRate: 0.08875, taxExempt: false } :
  userState === 'DE' ? { taxRate: 0, taxExempt: true } :
  { taxRate: 0.06, taxExempt: false }; // default

// Output the results
console.log(`User State: ${userState}`);
console.log(`Tax Rate: ${taxRate}`);
console.log(`Tax Exempt: ${taxExempt}`);

Output:

Ternary Operator Advance pattern in TypeScript

Best Practices for Using Ternary Operators

After years of TypeScript development, I’ve developed some guidelines for using ternaries effectively:

  1. Keep it simple – If your ternary becomes complex, consider refactoring
  2. Format for readability – Use line breaks and indentation for multi-line ternaries
  3. Avoid side effects – Ternaries should compute values, not perform actions
  4. Be consistent – Use ternaries throughout your codebase in a similar style
// Good formatting for complex ternaries
const shippingCost: number = 
  weight < 1 
    ? 3.99
    : weight < 5
      ? 5.99
      : weight < 10
        ? 9.99
        : 19.99;

Output:

Complex Ternary Operator in TypeScript

Check out:  Use For Loop Range in TypeScript

When NOT to Use Ternary Operators

While ternaries are powerful, they aren’t always the right choice:

// DON'T do this - too complex
const complexCalc = a > b 
  ? c > d 
    ? e + f 
    : g + h 
  : i > j 
    ? k + l 
    : m + n;

// Instead, use intermediate variables or functions
const firstComparison = a > b;
const secondComparison = c > d;
const thirdComparison = i > j;

const complexCalc = firstComparison
  ? (secondComparison ? e + f : g + h)
  : (thirdComparison ? k + l : m + n);

The ternary operator is a powerful tool in TypeScript that helps write cleaner, more concise code. It’s especially useful for simple conditional assignments, component rendering in React, and providing fallback values. However, it’s important to use it judiciously to maintain code readability.

Conclusion

In this TypeScript tutorial, we have learned how to use the ternary operator in TypeScript to write cleaner and more readable code. We have learned how to replace traditional if-else statements with the ternary operator. It can be used with TypeScript types, handle multiple conditions, and format dynamic messages.

When using ternary operators, always remember to use them to simplify the code and avoid them when the code becomes too complex.

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.