Live streamJoin us for "State of code review 2024" on July 18thRegister today

Operators in TypeScript

Kenny DuMez
Kenny DuMez
Graphite software engineer

TypeScript, a superset of JavaScript, introduces several enhancements to the language, including additional operators and improved type checking. This guide will cover the fundamental and advanced operators in TypeScript, providing a clear understanding of their syntax and practical usage. We'll explore various operators such as the ternary operator, spread operator, and more.

TypeScript supports standard arithmetic operators such as addition (+), subtraction (-), multiplication (*), and division (/). These operators work similarly to other C-like languages, allowing you to perform mathematical calculations.

Terminal
let a = 5
let b = 3
console.log(a + b) // output: 8
console.log(a - b) // output: 2
console.log(a * b) // output: 15
console.log(a / b) // output: 1.6666666666666667

Assignment operators in TypeScript are used to assign values to variables. The most basic operator is the simple assignment operator (=), which assigns the right-hand operand to the left-hand operand. Other compound operators, like +=, -=, *=, and /=, perform an operation and assignment in one step.

Terminal
let x = 10
x += 5 // equivalent to x = x + 5
console.log(x) // output: 15

Comparison operators compare two values and return a Boolean value, true or false. These include:

  • == (equality)
  • === (strict equality)
  • != (inequality)
  • !== (strict inequality)
  • > (greater than)
  • < (less than)
  • >= (greater than or equal to)
  • <= (less than or equal to)
Terminal
let num1 = 5,
num2 = '5',
num3 = 10
console.log(num1 == num2) // output: true
console.log(num1 === num2) // output: false
console.log(num1 < num3) // output: true

In TypeScript, as in JavaScript, the ==, and === operators, along with their negative counterparts !=, and !==, are used for comparing values, but they differ significantly in how they handle type coercion:

  • == (equality operator): This operator tests for abstract equality. It converts both operands to a common type before making the comparison. For example, if you compare a number with a string, the string is converted to a number before the comparison is made. This can lead to somewhat unexpected results where "2" == 2 evaluates to true.

  • === (strict equality operator): This operator tests for strict equality, meaning that it does not perform type conversion. If the values being compared have different types, the comparison will immediately return false. For example, "2" === 2 would evaluate to false because one is a string and the other is a number. This operator is generally recommended for use over == in TypeScript (and JavaScript) to avoid errors related to type coercion.

=== and !=== check both value and type, which leads to more predictable and safer code, whereas == and !== only check the value after performing type coercion, which can introduce subtle bugs.

Logical operators are used to determine the logic between variables or values:

  • && (logical and)
  • || (logical or)
  • ! (logical not)
Terminal
let condition1 = true,
condition2 = false
console.log(condition1 && condition2) // output: false
console.log(condition1 || condition2) // output: true
console.log(!condition1) // output: false

The logical operators &&, ||, and ! are used to combine or invert boolean values. The && operator (logical AND) returns true only if both operands are true; in the example, condition1 && condition2 returns false because condition2 is false. The || operator (logical OR) returns true if at least one of the operands is true, which is why condition1 || condition2 evaluates to true, and the ! operator (logical NOT) inverses the boolean value of its operand, making !condition1 return false since condition1 is true.

The ternary operator <condition> ? <output> : <output> in TypeScript is a shorthand for the if-else statement, which is used to assign a value to a variable based on some specified condition.

Terminal
let age = 18
let canVote = age >= 18 ? 'Yes' : 'No'
console.log(canVote) // output: Yes

This can be interpreted as if age is greater than or equal to 18 return Yes else return No.

The spread operator (...) allows an iterable such as an array or string to be expanded in places where zero or more arguments (for function calls) or elements (for array literals) are expected.

Terminal
let parts = ['shoulders', 'knees']
let lyrics = ['head', ...parts, 'and', 'toes']
console.log(lyrics) // output: ["head", "shoulders", "knees", "and", "toes"]

The in operator returns true if the specified property is contained in the specified object or its prototype chain.

Terminal
let car = { make: 'Toyota', model: 'Corolla' }
console.log('make' in car) // output: true

In TypeScript, the question mark is used in two contexts. First, it can be used to denote optional properties in interfaces or objects. Second, it serves as a part of the optional chaining operator (?.), which allows you to safely access deeply nested properties.

Terminal
interface Person {
name: string
age?: number // age is optional
}
let person: Person = { name: 'Alice' }
console.log(person.age ? person.age : 'Age not provided') // output: Age not provided
let obj = { a: { b: { c: 1 } } }
console.log(obj?.a?.b?.c) // output: 1

For further reading on TypeScript operators, see the official TypeScript documentation.

Stay unblocked. Ship faster.
Experience the new developer workflow - create, review, and merge code continuously. Get started with one command.
Get started

Give your PR workflow
an upgrade today

Stack easier | Ship smaller | Review quicker

Or install our CLI.
Product Screenshot 1
Product Screenshot 2