Typescript conditional (ternary) operator
Created By: chatGPT
In TypeScript, the conditional (ternary) operator is a concise way to perform conditional evaluations. The syntax is:
condition ? expressionIfTrue : expressionIfFalse
. It evaluates the condition, and if true, it returns the first expression; otherwise, it returns the second expression. This operator is particularly useful for inline conditional declarations.const age = 18;
const beverage = age >= 21 ? 'Beer' : 'Juice';
console.log(beverage); // Output: Juice
You can also use the ternary operator for more complex conditions and return values. For instance, you can nest multiple ternary operators to handle several outcomes, though it can make the code less readable if overused.
const score = 85;
const grade = score >= 90 ? 'A' :
score >= 80 ? 'B' :
score >= 70 ? 'C' :
score >= 60 ? 'D' : 'F';
console.log(grade); // Output: B
TypeScript also allows you to use the ternary operator within JSX for rendering components conditionally in frameworks like React. This is especially useful when you want to optionally display components based on certain conditions.
const isLoggedIn = true;
const greeting = isLoggedIn ? <h1>Welcome back!</h1> : <h1>Please log in.</h1>;
return <div>{greeting}</div>;
While the ternary operator is handy, it's important to maintain code readability. If your conditionals are getting complicated, consider using standard if-else statements instead for clarity.
const userRole = 'admin';
let accessLevel;
if (userRole === 'admin') {
accessLevel = 'Full access';
} else if (userRole === 'editor') {
accessLevel = 'Edit access';
} else {
accessLevel = 'View access';
}
console.log(accessLevel); // Output: Full access