Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 96 ยท Basic Types

Operators in TypeScript

A practical guide to TypeScript operators - arithmetic, comparison, logical, bitwise, assignment, nullish and optional chaining, plus the type-aware operators typeof, instanceof, in, keyof, as and satisfies.

Operators are the symbols that combine values: +, ===, &&, ?? and so on. They behave exactly as they do in JavaScript. What TypeScript adds is a layer of checking: it refuses nonsense such as subtracting a string from a number, and it uses some operators as type guards that make a type narrower inside a branch.

This lesson walks through the operator families with the typing rules you need to know. The last section covers the operators that exist only in TypeScript's type system.

Arithmetic operators

+, -, *, /, % and ** work on number and bigint. The unary ++ and -- change a variable in place.

TypeScript Arithmetic and its type rules

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The + operator is the one overloaded case. If either side is a string, the result is a string. Everything else (-, *, /) accepts only numeric types. That rule catches many bugs that JavaScript silently turns into NaN.

Comparison operators

<, >, <= and >= compare numbers with numbers and strings with strings. Use strict equality, === and !==. The loose == converts types before comparing, and TypeScript flags comparisons that can never be true:

TypeScript Strict equality and impossible comparisons

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The TS2367 check is a quiet superpower. Because status is a literal union, a typo in the comparison value is a compile error.

Logical operators and short-circuiting

&&, || and ! work on any value, not just booleans. && and || return one of their operands, and they stop evaluating as soon as the answer is known:

TypeScript Logical operators return operands

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Look at the type of label: false | "Administrator". TypeScript tracks which operand can come out. This matters in JSX, where {count && <p>...</p>} renders a literal 0 when count is 0.

Nullish coalescing and optional chaining

|| treats 0, '' and false as missing. That is often wrong for numbers and strings the user typed on purpose. The nullish coalescing operator ?? only replaces null and undefined. Optional chaining ?. stops safely when something is null or undefined.

TypeScript ?? and ?. versus ||

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

The logical assignment operators &&=, ||= and ??= combine a test and an assignment in one step.

Assignment operators

= assigns. Compound forms like +=, -=, *=, **= do the operation and assign. TypeScript checks that the result still fits the variable's type:

TypeScript
let total = 10;
total += 5;        // fine
// total += 'px';  // error TS2322: Type 'string' is not assignable to type 'number'.

let text = 'v';
text += 1;         // fine: the result is a string

Destructuring and spread also use = and ..., and are typed per element. Those are covered in Arrays and Tuples and Objects.

Bitwise operators

&, |, ^, ~, <<, >> and >>> work on the 32-bit integer form of a number. They are handy for flags and masks:

TypeScript Bit flags with literal constants

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Bit flags are also what numeric enums are sometimes used for, though a set of boolean fields is usually clearer.

The ternary operator

condition ? a : b is the only operator with three operands. The type of the whole expression is the union of both branches:

TypeScript
const age = 20;
const label = age >= 18 ? 'adult' : 'minor'; // type: "adult" | "minor"
const mixed = age >= 18 ? 'adult' : 0;       // type: 0 | "adult"

Keep ternaries short. Nested ternaries are hard to read; use if or a small function instead.

Operators that narrow types

Four operators double as type guards. TypeScript understands them in conditions and narrows the type inside the branch (see Narrowing):

TypeScript typeof, instanceof, in and equality narrow types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

  • typeof x === '...' narrows to primitive types.
  • x instanceof Class narrows to a class instance.
  • 'key' in x narrows to the union members that have that property.
  • === with a literal or null narrows by value.

Type-level operators

A few operators exist only in the type world and are erased when the code runs.

Operator Where What it does
typeof x (in a type position) Types Gets the type of a value: type P = typeof point
keyof T Types The union of the keys of T
T[K] Types Indexed access: the type of property K of T
x as T Expressions Type assertion: you override the compiler
x satisfies T Expressions Checks x against T without widening its type
x! Expressions Non-null assertion: removes null and undefined from the type
A | B, A & B Types Union and intersection
TypeScript typeof, keyof, as and satisfies in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

as and ! are promises you make to the compiler; they cost nothing at runtime and are not checked. Use them sparingly. See Type Assertions, keyof and typeof and satisfies for the full stories.

Operator precedence

When operators mix, precedence decides the order. Use parentheses whenever the order is not obvious. Two rules worth remembering: && binds tighter than ||, and ?? cannot be mixed with && or || without parentheses:

TypeScript
const a = true || false && false;     // true, && runs first
// const b = x ?? y || z;             // error TS5076: '??' and '||' operations cannot be mixed without parentheses.
const c = (null ?? 'x') || 'y';       // fine, explicit

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the result of '5' + 2 in TypeScript?

    + concatenates when either operand is a string. TypeScript allows it and infers string.
  2. 2. Which expression returns 0 when value is 0?

    ?? only falls back for null and undefined. || treats 0 as missing, and && would return 0 only by accident.
  3. 3. Why does if (status === 'pending') fail to compile when status is 'open' | 'closed'?

    TypeScript compares the types on both sides and reports comparisons that cannot succeed.
  4. 4. What does 'meow' in value do for a union of Cat | Dog?

    The in operator is a type guard. Inside the true branch, value is Cat.
  5. 5. Which operator exists only in the type system and is erased at runtime?

    keyof T produces a type and has no runtime form. The expression typeof x in a condition does exist at runtime.

Summary

  • Arithmetic works on number and bigint (never mixed); + also concatenates when a string is involved.
  • Use === and !==. TypeScript reports comparisons between types that cannot overlap.
  • && and || return operands. Use ?? and ?. for null and undefined, and ??=, ||=, &&= for conditional assignment.
  • Bitwise operators suit flags and masks on 32-bit integers.
  • typeof, instanceof, in and === narrow types in conditions.
  • keyof, type-position typeof, T[K], as, satisfies and ! are type-system tools with no runtime cost.

Next: Arrays and Tuples