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.
Arithmetic operators
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.
let a = 5let b = 3console.log(a + b) // output: 8console.log(a - b) // output: 2console.log(a * b) // output: 15console.log(a / b) // output: 1.6666666666666667
Assignment operators
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.
let x = 10x += 5 // equivalent to x = x + 5console.log(x) // output: 15
Comparison operators
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)
let num1 = 5,num2 = '5',num3 = 10console.log(num1 == num2) // output: trueconsole.log(num1 === num2) // output: falseconsole.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 totrue
.===
(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 returnfalse
. For example,"2" === 2
would evaluate tofalse
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
Logical operators are used to determine the logic between variables or values:
&&
(logical and)||
(logical or)!
(logical not)
let condition1 = true,condition2 = falseconsole.log(condition1 && condition2) // output: falseconsole.log(condition1 || condition2) // output: trueconsole.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.
Ternary operator (conditional operator)
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.
let age = 18let 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
.
Spread operator
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.
let parts = ['shoulders', 'knees']let lyrics = ['head', ...parts, 'and', 'toes']console.log(lyrics) // output: ["head", "shoulders", "knees", "and", "toes"]
in
operator
The in
operator returns true
if the specified property is contained in the specified object or its prototype chain.
let car = { make: 'Toyota', model: 'Corolla' }console.log('make' in car) // output: true
TypeScript's type-specific operators
The question mark operator (?
)
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.
interface Person {name: stringage?: number // age is optional}let person: Person = { name: 'Alice' }console.log(person.age ? person.age : 'Age not provided') // output: Age not providedlet obj = { a: { b: { c: 1 } } }console.log(obj?.a?.b?.c) // output: 1
For further reading on TypeScript operators, see the official TypeScript documentation.