• DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter

TypeScript Operators

  • Typescript Keyof Type Operator
  • TypeScript Constraints
  • TypeScript Instanceof Operator
  • TypeScript Object
  • TypeScript Tuples
  • TypeScript Arrays
  • TypeScript Numbers
  • TypeScript Literal Types
  • TypeScript class
  • TypeScript Optional Parameters
  • TypeScript Map
  • TypeScript Object Types
  • TypeScript Mapped Types
  • TypeScript Assertions Type
  • Rest Parameters in TypeScript
  • Interfaces in TypeScript
  • TypeScript Generic Types
  • Next.js TypeScript
  • TypeScript in operator narrowing Type

TypeScript operators are symbols or keywords that perform operations on one or more operands. In this article, we are going to learn various types of TypeScript Operators.

Below are the different TypeScript Operators:

Table of Content

TypeScript Arithmetic operators

Typescript logical operators, typescript relational operators, typescript bitwise operators, typescript assignment operators, typescript ternary/conditional operator, typescript type operators, typescript string operators.

In TypeScript, arithmetic operators are used to perform mathematical calculations.

In TypeScript, logical operators are used to perform logical operations on Boolean values.

In TypeScript, relational operators are used to compare two values and determine the relationship between them.

In TypeScript, bitwise operators perform operations on the binary representation of numeric values.

In TypeScript, assignment operators are used to assign values to variables and modify their values based on arithmetic or bitwise operations.

In TypeScript, the ternary operator, also known as the conditional operator, is a concise way to write conditional statements. It allows you to express a simple if-else statement in a single line.

In TypeScript, type operators are constructs that allow you to perform operations on types. These operators provide powerful mechanisms for defining and manipulating types in a flexible and expressive manner.

In TypeScript, string operators and features are used for manipulating and working with string values.

Please Login to comment...

Similar reads.

  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

TypeScript 4.0

Variadic tuple types.

Consider a function in JavaScript called concat that takes two array or tuple types and concatenates them together to make a new array.

Also consider tail , that takes an array or tuple, and returns all elements but the first.

How would we type either of these in TypeScript?

For concat , the only valid thing we could do in older versions of the language was to try and write some overloads.

Uh…okay, that’s…seven overloads for when the second array is always empty. Let’s add some for when arr2 has one argument.

We hope it’s clear that this is getting unreasonable. Unfortunately, you’d also end up with the same sorts of issues typing a function like tail .

This is another case of what we like to call “death by a thousand overloads”, and it doesn’t even solve the problem generally. It only gives correct types for as many overloads as we care to write. If we wanted to make a catch-all case, we’d need an overload like the following:

But that signature doesn’t encode anything about the lengths of the input, or the order of the elements, when using tuples.

TypeScript 4.0 brings two fundamental changes, along with inference improvements, to make typing these possible.

The first change is that spreads in tuple type syntax can now be generic. This means that we can represent higher-order operations on tuples and arrays even when we don’t know the actual types we’re operating over. When generic spreads are instantiated (or, replaced with a real type) in these tuple types, they can produce other sets of array and tuple types.

For example, that means we can type function like tail , without our “death by a thousand overloads” issue.

The second change is that rest elements can occur anywhere in a tuple - not just at the end!

Previously, TypeScript would issue an error like the following:

But with TypeScript 4.0, this restriction is relaxed.

Note that in cases when we spread in a type without a known length, the resulting type becomes unbounded as well, and all the following elements factor into the resulting rest element type.

By combining both of these behaviors together, we can write a single well-typed signature for concat :

While that one signature is still a bit lengthy, it’s just one signature that doesn’t have to be repeated, and it gives predictable behavior on all arrays and tuples.

This functionality on its own is great, but it shines in more sophisticated scenarios too. For example, consider a function to partially apply arguments called partialCall . partialCall takes a function - let’s call it f - along with the initial few arguments that f expects. It then returns a new function that takes any other arguments that f still needs, and calls f when it receives them.

TypeScript 4.0 improves the inference process for rest parameters and rest tuple elements so that we can type this and have it “just work”.

In this case, partialCall understands which parameters it can and can’t initially take, and returns functions that appropriately accept and reject anything left over.

Variadic tuple types enable a lot of new exciting patterns, especially around function composition. We expect we may be able to leverage it to do a better job type-checking JavaScript’s built-in bind method. A handful of other inference improvements and patterns also went into this, and if you’re interested in learning more, you can take a look at the pull request for variadic tuples.

Labeled Tuple Elements

Improving the experience around tuple types and parameter lists is important because it allows us to get strongly typed validation around common JavaScript idioms - really just slicing and dicing argument lists and passing them to other functions. The idea that we can use tuple types for rest parameters is one place where this is crucial.

For example, the following function that uses a tuple type as a rest parameter…

…should appear no different from the following function…

…for any caller of foo .

There is one place where the differences begin to become observable though: readability. In the first example, we have no parameter names for the first and second elements. While these have no impact on type-checking, the lack of labels on tuple positions can make them harder to use - harder to communicate our intent.

That’s why in TypeScript 4.0, tuples types can now provide labels.

To deepen the connection between parameter lists and tuple types, the syntax for rest elements and optional elements mirrors the syntax for parameter lists.

There are a few rules when using labeled tuples. For one, when labeling a tuple element, all other elements in the tuple must also be labeled.

It’s worth noting - labels don’t require us to name our variables differently when destructuring. They’re purely there for documentation and tooling.

Overall, labeled tuples are handy when taking advantage of patterns around tuples and argument lists, along with implementing overloads in a type-safe way. In fact, TypeScript’s editor support will try to display them as overloads when possible.

To learn more, check out the pull request for labeled tuple elements.

Class Property Inference from Constructors

TypeScript 4.0 can now use control flow analysis to determine the types of properties in classes when noImplicitAny is enabled.

In cases where not all paths of a constructor assign to an instance member, the property is considered to potentially be undefined .

In cases where you know better (e.g. you have an initialize method of some sort), you’ll still need an explicit type annotation along with a definite assignment assertion ( ! ) if you’re in strictPropertyInitialization .

For more details, see the implementing pull request .

Short-Circuiting Assignment Operators

JavaScript, and a lot of other languages, support a set of operators called compound assignment operators. Compound assignment operators apply an operator to two arguments, and then assign the result to the left side. You may have seen these before:

So many operators in JavaScript have a corresponding assignment operator! Up until recently, however, there were three notable exceptions: logical and ( && ), logical or ( || ), and nullish coalescing ( ?? ).

That’s why TypeScript 4.0 supports a new ECMAScript feature to add three new assignment operators: &&= , ||= , and ??= .

These operators are great for substituting any example where a user might write code like the following:

Or a similar if block like

There are even some patterns we’ve seen (or, uh, written ourselves) to lazily initialize values, only if they’ll be needed.

(look, we’re not proud of all the code we write…)

On the rare case that you use getters or setters with side-effects, it’s worth noting that these operators only perform assignments if necessary. In that sense, not only is the right side of the operator “short-circuited” - the assignment itself is too.

Try running the following example to see how that differs from always performing the assignment.

We’d like to extend a big thanks to community member Wenlu Wang for this contribution!

For more details, you can take a look at the pull request here . You can also check out TC39’s proposal repository for this feature .

unknown on catch Clause Bindings

Since the beginning days of TypeScript, catch clause variables have always been typed as any . This meant that TypeScript allowed you to do anything you wanted with them.

The above has some undesirable behavior if we’re trying to prevent more errors from happening in our error-handling code! Because these variables have the type any by default, they lack any type-safety which could have errored on invalid operations.

That’s why TypeScript 4.0 now lets you specify the type of catch clause variables as unknown instead. unknown is safer than any because it reminds us that we need to perform some sorts of type-checks before operating on our values.

While the types of catch variables won’t change by default, we might consider a new strict mode flag in the future so that users can opt in to this behavior. In the meantime, it should be possible to write a lint rule to force catch variables to have an explicit annotation of either : any or : unknown .

For more details you can peek at the changes for this feature .

Custom JSX Factories

When using JSX, a fragment is a type of JSX element that allows us to return multiple child elements. When we first implemented fragments in TypeScript, we didn’t have a great idea about how other libraries would utilize them. Nowadays most other libraries that encourage using JSX and support fragments have a similar API shape.

In TypeScript 4.0, users can customize the fragment factory through the new jsxFragmentFactory option.

As an example, the following tsconfig.json file tells TypeScript to transform JSX in a way compatible with React, but switches each factory invocation to h instead of React.createElement , and uses Fragment instead of React.Fragment .

In cases where you need to have a different JSX factory on a per-file basis , you can take advantage of the new /** @jsxFrag */ pragma comment. For example, the following…

…will get transformed to this output JavaScript…

We’d like to extend a big thanks to community member Noj Vek for sending this pull request and patiently working with our team on it.

You can see that the pull request for more details!

Speed Improvements in build mode with --noEmitOnError

Previously, compiling a program after a previous compile with errors under incremental would be extremely slow when using the noEmitOnError flag. This is because none of the information from the last compilation would be cached in a .tsbuildinfo file based on the noEmitOnError flag.

TypeScript 4.0 changes this which gives a great speed boost in these scenarios, and in turn improves --build mode scenarios (which imply both incremental and noEmitOnError ).

For details, read up more on the pull request .

--incremental with --noEmit

TypeScript 4.0 allows us to use the noEmit flag when while still leveraging incremental compiles. This was previously not allowed, as incremental needs to emit a .tsbuildinfo files; however, the use-case to enable faster incremental builds is important enough to enable for all users.

For more details, you can see the implementing pull request .

Editor Improvements

The TypeScript compiler doesn’t only power the editing experience for TypeScript itself in most major editors - it also powers the JavaScript experience in the Visual Studio family of editors and more. For that reason, much of our work focuses on improving editor scenarios - the place you spend most of your time as a developer.

Using new TypeScript/JavaScript functionality in your editor will differ depending on your editor, but

  • Visual Studio Code supports selecting different versions of TypeScript . Alternatively, there’s the JavaScript/TypeScript Nightly Extension to stay on the bleeding edge (which is typically very stable).
  • Visual Studio 2017/2019 have [the SDK installers above] and MSBuild installs .
  • Sublime Text 3 supports selecting different versions of TypeScript

You can check out a partial list of editors that have support for TypeScript to learn more about whether your favorite editor has support to use new versions.

Convert to Optional Chaining

Optional chaining is a recent feature that’s received a lot of love. That’s why TypeScript 4.0 brings a new refactoring to convert common patterns to take advantage of optional chaining and nullish coalescing !

Keep in mind that while this refactoring doesn’t perfectly capture the same behavior due to subtleties with truthiness/falsiness in JavaScript, we believe it should capture the intent for most use-cases, especially when TypeScript has more precise knowledge of your types.

For more details, check out the pull request for this feature .

/** @deprecated */ Support

TypeScript’s editing support now recognizes when a declaration has been marked with a /** @deprecated */ JSDoc comment. That information is surfaced in completion lists and as a suggestion diagnostic that editors can handle specially. In an editor like VS Code, deprecated values are typically displayed a strike-though style like this .

Some examples of deprecated declarations with strikethrough text in the editor

This new functionality is available thanks to Wenlu Wang . See the pull request for more details.

Partial Semantic Mode at Startup

We’ve heard a lot from users suffering from long startup times, especially on bigger projects. The culprit is usually a process called program construction . This is the process of starting with an initial set of root files, parsing them, finding their dependencies, parsing those dependencies, finding those dependencies’ dependencies, and so on. The bigger your project is, the longer you’ll have to wait before you can get basic editor operations like go-to-definition or quick info.

That’s why we’ve been working on a new mode for editors to provide a partial experience until the full language service experience has loaded up. The core idea is that editors can run a lightweight partial server that only looks at the current files that the editor has open.

It’s hard to say precisely what sorts of improvements you’ll see, but anecdotally, it used to take anywhere between 20 seconds to a minute before TypeScript would become fully responsive on the Visual Studio Code codebase. In contrast, our new partial semantic mode seems to bring that delay down to just a few seconds . As an example, in the following video, you can see two side-by-side editors with TypeScript 3.9 running on the left and TypeScript 4.0 running on the right.

When restarting both editors on a particularly large codebase, the one with TypeScript 3.9 can’t provide completions or quick info at all. On the other hand, the editor with TypeScript 4.0 can immediately give us a rich experience in the current file we’re editing, despite loading the full project in the background.

Currently the only editor that supports this mode is Visual Studio Code which has some UX improvements coming up in Visual Studio Code Insiders . We recognize that this experience may still have room for polish in UX and functionality, and we have a list of improvements in mind. We’re looking for more feedback on what you think might be useful.

For more information, you can see the original proposal , the implementing pull request , along with the follow-up meta issue .

Smarter Auto-Imports

Auto-import is a fantastic feature that makes coding a lot easier; however, every time auto-import doesn’t seem to work, it can throw users off a lot. One specific issue that we heard from users was that auto-imports didn’t work on dependencies that were written in TypeScript - that is, until they wrote at least one explicit import somewhere else in their project.

Why would auto-imports work for @types packages, but not for packages that ship their own types? It turns out that auto-imports only work on packages your project already includes. Because TypeScript has some quirky defaults that automatically add packages in node_modules/@types to your project, those packages would be auto-imported. On the other hand, other packages were excluded because crawling through all your node_modules packages can be really expensive.

All of this leads to a pretty lousy getting started experience for when you’re trying to auto-import something that you’ve just installed but haven’t used yet.

TypeScript 4.0 now does a little extra work in editor scenarios to include the packages you’ve listed in your package.json ’s dependencies (and peerDependencies ) fields. The information from these packages is only used to improve auto-imports, and doesn’t change anything else like type-checking. This allows us to provide auto-imports for all of your dependencies that have types, without incurring the cost of a complete node_modules search.

In the rare cases when your package.json lists more than ten typed dependencies that haven’t been imported yet, this feature automatically disables itself to prevent slow project loading. To force the feature to work, or to disable it entirely, you should be able to configure your editor. For Visual Studio Code, this is the “Include Package JSON Auto Imports” (or typescript.preferences.includePackageJsonAutoImports ) setting.

Configuring 'include package JSON auto imports'

Our New Website!

The TypeScript website has recently been rewritten from the ground up and rolled out!

A screenshot of the new TypeScript website

We already wrote a bit about our new site , so you can read up more there; but it’s worth mentioning that we’re still looking to hear what you think! If you have questions, comments, or suggestions, you can file them over on the website’s issue tracker .

Breaking Changes

Lib.d.ts changes.

Our lib.d.ts declarations have changed - most specifically, types for the DOM have changed. The most notable change may be the removal of document.origin which only worked in old versions of IE and Safari MDN recommends moving to self.origin .

Properties Overriding Accessors (and vice versa) is an Error

Previously, it was only an error for properties to override accessors, or accessors to override properties, when using useDefineForClassFields ; however, TypeScript now always issues an error when declaring a property in a derived class that would override a getter or setter in the base class.

See more details on the implementing pull request .

Operands for delete must be optional.

When using the delete operator in strictNullChecks , the operand must now be any , unknown , never , or be optional (in that it contains undefined in the type). Otherwise, use of the delete operator is an error.

Usage of TypeScript’s Node Factory is Deprecated

Today TypeScript provides a set of “factory” functions for producing AST Nodes; however, TypeScript 4.0 provides a new node factory API. As a result, for TypeScript 4.0 we’ve made the decision to deprecate these older functions in favor of the new ones.

For more details, read up on the relevant pull request for this change .

Nightly Builds

How to use a nightly build of TypeScript

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request ❤

Orta Therox  (6)

Last updated: May 16, 2024  

Popular Articles

  • Boolean (May 18, 2024)
  • Satisfies Keyword (May 18, 2024)
  • Non-Null Assertion (May 18, 2024)
  • As Any (May 18, 2024)
  • As [Type] (May 18, 2024)

TypeScript Operator

Switch to English

Table of Contents

Types of TypeScript Operators

Arithmetic operators, logical operators, relational operators, bitwise operators, assignment operators, ternary/conditional operators, string operators, type operators, tips and common error-prone cases.

Introduction Understanding TypeScript operators is a fundamental part of learning TypeScript. TypeScript operators are symbols used to perform operations on operands. An operand can be a variable, a value, or a literal.

  • Ternary/conditional Operators
  • Always use '===' instead of '==' for comparisons to avoid type coercion.
  • Remember that the '&&' and '||' operators return a value of one of the operands, not necessarily a boolean.
  • Be careful when using bitwise operators as they can lead to unexpected results due to JavaScript's internal number representation.
  • Use parentheses to ensure correct order of operations when combining operators in complex expressions.
  • Remember that the '+' operator behaves differently with strings, leading to unexpected results.

MarketSplash

Getting To Know Typescript Operators In Depth

Dive deep into TypeScript operators, the building blocks that enhance code efficiency and readability. From arithmetic to relational, get a grasp on how each operator functions and elevates your coding prowess. Join us on this coding journey!

đź’ˇ KEY INSIGHTS

  • The 'in' operator in TypeScript is crucial for checking property existence in objects, enhancing code reliability and error handling.
  • It is particularly useful in interfaces and dynamic property checking , ensuring objects conform to expected structures.
  • The article points out common pitfalls, like confusing property existence with truthy values and overlooking the prototype chain.
  • It also compares 'in' with other operators, highlighting its unique functionality in TypeScript.

Typescript operators play a pivotal role in shaping the way we handle data and logic in our applications. As a cornerstone of the language, understanding these operators is essential for efficient coding. This knowledge not only streamlines development but also enhances code readability and maintainability. Let's explore the nuances of these operators to elevate our Typescript proficiency.

assignment operators typescript

Basics Of Typescript Operators

Arithmetic operators in typescript, logical operators: true or false, relational operators: comparing values, bitwise operators: manipulating bits, assignment operators: setting values, ternary operator: conditional expressions, type operators: defining types, spread and rest operators: working with arrays and objects, frequently asked questions, arithmetic operators, logical operators, bitwise operators, relational operators, assignment operators, ternary operator, concatenation operator, type operators.

assignment operators typescript

Arithmetic operators like + , - , * , and / allow us to perform basic mathematical operations.

With logical operators such as && , || , and ! , we can establish conditions and logic flows.

Bitwise operators like & , | , and ^ operate on individual bits of numbers.

Relational operators, including == , != , > , and < , help us compare values.

Assignment operators, such as = , += , and -= , assign values to variables.

The ternary operator ? : provides a shorthand way to perform conditional operations.

In Typescript, the + operator can also concatenate strings.

Type operators like typeof and instanceof help in determining the type of a variable or checking its instance.

Arithmetic operators in Typescript are essential for performing mathematical operations on numbers. They're the basic tools that allow us to add, subtract, multiply, and more.

Addition Operator

Subtraction operator, multiplication operator, division operator, modulus operator, increment and decrement, exponentiation operator.

The + operator adds two numbers together.

The - operator subtracts one number from another.

With the * operator, we can multiply two numbers.

The / operator divides one number by another.

The % operator returns the remainder of a division.

The ++ and -- operators increase or decrease a number by one, respectively.

The ** operator raises a number to the power of another number.

Logical operators in Typescript are used to determine the truthiness of conditions. They play a crucial role in decision-making structures, allowing us to evaluate multiple conditions.

AND Operator

Or operator, not operator.

The && operator returns true if both conditions are true.

The || operator returns true if at least one of the conditions is true.

The ! operator inverts the truthiness of a condition.

While not purely logical, the ternary ? : operator allows for concise conditional checks.

The exclamation mark ( ! ) operator following node.parent caught attention. An initial attempt to compile the file using TypeScript version 1.5.3 resulted in an error pinpointing the exact location of this operator. However, after upgrading to TypeScript 2.1.6, the code compiled seamlessly. Interestingly, the transpiled JavaScript omitted the exclamation mark:

This operator is known as the non-null assertion operator . It serves as a directive to the compiler, indicating that "the expression at this location is neither null nor undefined." There are instances where the type checker might not deduce this on its own.

Relational operators in Typescript are pivotal for comparing values. They help determine relationships between variables, enabling us to make decisions based on these comparisons.

Not Equal To

Greater than and less than, greater than or equal to, less than or equal to.

The == operator checks if two values are equal.

The != operator checks if two values are not equal.

The > and < operators compare the magnitude of values.

The >= and <= operators offer inclusive comparisons.

Bitwise operators in Typescript allow for direct manipulation of individual bits within numbers. These operators are especially useful in low-level programming, offering precise control over data at the bit level.

Bitwise AND

Bitwise xor, bitwise not, left and right shift.

The & operator performs a bitwise AND operation.

The | operator performs a bitwise OR operation.

The ^ operator is used for the bitwise XOR operation.

The ~ operator inverts all bits.

The << and >> operators shift bits to the left or right, respectively.

Assignment operators in Typescript are fundamental tools that allow us to assign values to variables. They not only set values but can also perform operations during the assignment, streamlining our code.

Basic Assignment

Addition assignment, subtraction assignment, multiplication and division assignment, modulus and exponentiation assignment.

The = operator assigns a value to a variable.

The += operator adds a value to a variable and then assigns the result to that variable.

The -= operator subtracts a value from a variable and then assigns the result.

The *= and /= operators multiply or divide a variable's value, respectively, and then assign the result.

The %= and **= operators assign the remainder of a division or the result of an exponentiation to a variable.

The ternary operator in Typescript offers a concise way to perform conditional checks. It's a shorthand for the if-else statement, allowing developers to write cleaner and more readable code.

Basic Usage

Nested ternary, using with functions.

The ternary operator is represented by ? : and is used to evaluate a condition, returning one value if the condition is true and another if it's false.

Ternary operators can be nested for multiple conditions, though it's essential to ensure readability.

The ternary operator can also be combined with functions to execute specific tasks based on conditions.

In Typescript , type operators play a crucial role in ensuring type safety. They allow developers to define, check, and manipulate types, ensuring that variables adhere to the expected data structures.

typeof Operator

Instanceof operator, custom type guards, type assertions.

The typeof operator returns a string indicating the type of a variable.

The instanceof operator checks if an object is an instance of a particular class or constructor.

Typescript allows developers to create custom type guards using the is keyword, ensuring more refined type checks.

Type assertions, using <Type> or as Type , allow developers to specify the type of an object explicitly.

In Typescript , the spread ( ... ) and rest ( ... ) operators provide powerful ways to work with arrays and objects. They offer concise syntax for expanding and collecting elements, making data manipulation more efficient.

Spread Operator

Rest operator.

The spread operator allows for the expansion of array elements or object properties.

For objects:

The rest operator is used to collect the remaining elements into an array or object properties into an object.

For function parameters:

Can TypeScript operators be overloaded like in some other languages?

No, TypeScript does not support operator overloading. The behavior of operators is fixed and cannot be changed for user-defined types. However, you can define custom methods for classes to achieve similar functionality.

How does the in operator work in TypeScript?

The in operator is used to determine if an object has a specific property. It returns true if the property is in the object (or its prototype chain) and false otherwise. For example, "name" in person would check if the person object has a property named "name".

What's the difference between == and === operators in TypeScript?

Both == and === are comparison operators, but they work differently. The == operator performs type coercion if the variables being compared are of different types, meaning it might convert one type to another for the comparison. On the other hand, === is a strict equality operator that checks both value and type, ensuring no type coercion occurs.

assignment operators typescript

How can I use the instanceof operator with custom classes in TypeScript?

The instanceof operator in TypeScript works similarly to JavaScript. It checks if an object is an instance of a particular class or constructor. For custom classes, you can use it like: let isStudent = person instanceof Student; , where Student is a user-defined class. If person is an instance of the Student class, isStudent will be true .

Let's see what you learned!

Which Operator Is Used In TypeScript To Specify An Optional Property?

Continue learning with these typescript guides.

  • How To Utilize TypeScript Decorators Effectively
  • How To Use TypeScript Extend Type Effectively
  • TypeScript Generics: A Path To Scalable Code
  • How To Use TypeScript Instanceof Effectively
  • How To Use The TypeScript Constructor Efficiently

Subscribe to our newsletter

Subscribe to be notified of new content on marketsplash..

  • TS Introduction
  • TS Operators
  • TS Control Flow
  • TS Data structures
  • TS Adv. Concepts
  • TS Adv. Programming
  • TS Essentials

Assignment Operators in TypeScript

TypeScript assignment operators are used to assign values to variables and expressions. They are the fundamental building blocks for manipulating data and updating the state of your program.

List of Assignment Operators

Here are the different assignment operators available in TypeScript:

  • Simple assignment (=): Assigns the right operand value to the left operand.
  • Addition assignment (+=): Adds the right operand to the left operand and assigns the result to the left operand.
  • Subtraction assignment (-=): Subtracts the right operand from the left operand and assigns the result to the left operand.
  • Multiplication assignment (*=): Multiplies the right operand with the left operand and assigns the result to the left operand.
  • Division assignment (/=): Divides the left operand by the right operand and assigns the result to the left operand.
  • Modulo assignment (%=): Finds the remainder of dividing the left operand by the right operand and assigns the result to the left operand.
  • Exponential assignment (**=): Raises the left operand to the power of the right operand and assigns the result to the left operand.
  • Left shift assignment ( Shifts the left operand bitwise to the left by the number of bits specified by the right operand and assigns the result to the left operand.
  • Right shift assignment (>>=): Shifts the left operand bitwise to the right by the number of bits specified by the right operand and assigns the result to the left operand.
  • Unsigned right shift assignment (>>>=): Shifts the left operand bitwise to the right by the number of bits specified by the right operand, treating the left operand as an unsigned integer, and assigns the result to the left operand.

Assignment (=) Operator

The basic assignment operator (=) is used to assign a value to a variable.

Compound Assignment Operators

Compound assignment operators combine an assignment with another operation, making it more concise. They include:

Addition Assignment (+=)

Subtraction assignment (-=), multiplication assignment (*=), division assignment (/=), modulus assignment (%=).

These compound assignment operators perform the specified operation and then assign the result back to the variable.

Exponentiation Assignment (**=)

The exponentiation assignment operator (**=) raises the left operand to the power of the right operand and assigns the result to the left operand.

Type Safety

TypeScript assignment operators ensure type safety by restricting assignments to compatible data types. This prevents errors and unexpected behavior due to mismatched types.

Operator Precedence

Assignment operators have a specific order of precedence within expressions. Understanding this order is crucial for accurate evaluation and avoiding ambiguity in your code.

Chaining Assignments

You can chain multiple assignment operators together to perform multiple operations with concise syntax.

TypeScript assignment operators, including the basic assignment (=) and compound assignments (+=, -=, *=, /=, %=), provide a concise way to assign values and perform compound operations on variables. These operators enhance code readability and efficiency by combining assignment with arithmetic or modulus operations in a single step.

  • TypeScript Arithmetic Operators
  • TypeScript Comparison Operators
  • TypeScript Logical Operators
  • TypeScript Unary operators
  • TypeScript Bitwise operators
  • Course List
  • Introduction to TypeScript
  • Environment Setup
  • Workspace & first app
  • Basic Syntax
  • Variables & Constants
  • Conditional Control
  • if, else if, else & switch
  • Iteration Control
  • for, while, do-while loops
  • Intermediate
  • Map Collections
  • Object Oriented Programming
  • OOP: Classes & Objects
  • OOP: Standalone Objects
  • OOP: Constructors
  • OOP: Property Modifiers
  • OOP: Access Modifiers
  • OOP: Parameter Properties
  • OOP: Getters & Setters
  • OOP: Static methods
  • OOP: Index Signatures
  • OOP: Inheritance
  • OOP: Composition
  • Compilation Config (tsconfig.json)

TypeScript Operators Tutorial

In this TypeScript tutorial we learn the standard arithmetic, assignment, comparison (relational) and logical (conditional) operators.

We also discuss the negation, concatenation, typeof and ternary operators as well as operator precedence in TypeScript.

  • What are operators
  • Arithmetic operators
  • Assignment operators
  • Comparison (Relational) operators
  • Logical (Conditional) operators
  • Other: The negation operator
  • Other: The concatenation operator
  • Other: The typeof operator
  • Other: The ternary operator
  • Operator precedence

Summary: Points to remember

Operators are one or more symbols in TypeScript that is special to the compiler and allows us to perform various operations within our application.

As an example, let’s consider the + symbol. The + symbol is an operator to perform arithmetic on two or more numeric values. But, when used on two or more strings, the + operator will combine (concatenate) them into a single string.

Types in TypeScript fall under the following categories:

  • Comparison (Relational)
  • Logical (Conditional)
  • Concatenation

TypeScript supports the following the arithmetic operators.

TypeScript supports the following assignment operators.

TypeScript supports the following comparison operators.

Typically, if we want to to turn a positive number into a negative number, we would have to multiply that number by -1.

The negation operator can turn a number negative simply be prefixing it with the - operator.

When working with arithmetic, the + operator will perform an addition. But, when working with strings, the + operator will combine (concatenate) the strings together.

The typeof operator will get and return the data type of the operand we specify.

The typeof operator is simply the keyword typeof .

The ternary operator is a shorthand method of writing a if/else statement that only contains a single execution statement.

note If this doesn’t make sense at the moment, don’t worry, we cover the ternary statement again the tutorial lesson on conditional control statements .

Let’s consider the following if else statement.

In the example above, we evaluate if a number is 10 or not and print a message to the console. Let’s convert this into shorthand with the ternary operator.

Certain operators in TypeScript will have higher precedence than others.

As an example, let’s consider the precedence of the multiplication and addition operators.

If we read the calculation from left to right, we would do the addition first. But, the multiplication operator has a higher precedence than the addition operator, so it will do that part of the calculation first.

We can change the operator precedence by wrapping operators in parentheses.

In the example above, we want the addition to be performed before the multiplication, so we wrap the addition in parentheses.

  • Operators are symbols that have a special meaning to the compiler.
  • TypeScript supports the typical arithmetic, assignment, comparison (relational) and logical (conditional) operators.
  • Typescript also supports the negation, concatenation, typeof and ternary operators.
  • Some operators have greater importance than others and we change operator precedence with parentheses.

assignment operators typescript

Announcing TypeScript 4.0

assignment operators typescript

Daniel Rosenwasser

August 20th, 2020 2 0

Today we are thrilled to announce the availability of TypeScript 4.0! This version of the language represents our next generation of TypeScript releases, as we dive deeper into expressivity, productivity, and scalability.

If you’re not familiar with TypeScript, it’s a language that builds on top of JavaScript by adding syntax for static types . The idea is that by writing down the types of your values and where they’re used, you can use TypeScript to type-check your code and tell you about mistakes before you run your code (and even before saving your file). You can then use the TypeScript compiler to then strip away types from your code, and leaving you with clean, readable JavaScript that runs anywhere. Beyond checking, TypeScript also uses static types to power great editor tooling like auto-completion, code navigation, refactorings, and more. In fact, if you’ve used JavaScript in an editor like Visual Studio Code or Visual Studio, you’ve already been using an experience powered by types and TypeScript. You can learn more about all of this on our website .

With TypeScript 4.0, there are no major breaking changes. In fact, if you’re new to the language, now is the best time to start using it. The community is already here and growing, with working code and great new resources to learn. And one thing to keep in mind: despite all the good stuff we’re bringing in 4.0, you really only need to know the basics of TypeScript to be productive!

If you’re already using TypeScript in your project, you can either get it through NuGet or use npm with the following command:

You can also get editor support by

  • Downloading for Visual Studio 2019/2017
  • Installing the Insiders Version of Visual Studio Code or following directions to use a newer version of TypeScript
  • Using PackageControl with Sublime Text 3 .

The 4.0 Journey

TypeScript is a core part of many people’s JavaScript stack today. On npm, TypeScript saw over 50 million monthly downloads for the first time in July! And while we recognize there’s always room for growth and improvement, it’s clear that most people coding in TypeScript really do enjoy it. StackOverflow’s most recent developer survey pins TypeScript as the 2nd most-loved language . In the most recent State of JS Survey, around 89% of developers who used TypeScript said that they would use it again .

It’s worth digging a bit into how we got here. In our past two major versions, we looked back at some highlights that shined over the years. For TypeScript 4.0, we’re going to keep up that tradition.

Looking back from 3.0 onward, there’s a dizzying number of changes, but TypeScript 3.0 itself came out with a punch. Unifying tuple types and parameter lists was a big highlight, enabling tons of existing JavaScript patterns on functions. The release also featured project references to help scale up, organize, and share across codebases. One small change that had a big impact was that 3.0 introduced a type-safe alternative to any called unknown .

TypeScript 3.1 extended the capabilities of mapped types to work on tuple and array types, and made it dramatically easier to attach properties to functions without resorting to TypeScript-specific runtime features that have fallen out of use.

TypeScript 3.2 allowed object spreads on generic types, and leveraged 3.0’s capabilities to better model meta-programming with functions by strictly typing bind , call , and apply . TypeScript 3.3 focused a bit on stability following 3.2, but also brought quality-of-life improvements when using union type methods, and added file-incremental builds under --build mode.

In the 3.4 release , we leaned farther into supporting functional patterns, with better support for immutable data structures, and improved inference on higher-order generic functions. As a big plus, this release introduced the --incremental flag, a way to get faster compiles and type-checks by avoiding a full rebuild on every run of TypeScript, without project references.

With TypeScript 3.5 and 3.6 , we saw some tightening up of the type system rules, along with smarter compatibility checking rules.

TypeScript 3.7 was a very noteworthy release because it featured a rich combination of new type system features with ECMAScript features. From the type-system side, we saw recursive type alias references and support for assertion-style functions, both which are unique type-system features. From the JavaScript side, the release brought optional chaining and coalescing, two of the most highly demanded features for TypeScript and JavaScript users alike, championed in TC39 in part by our team.

Much more recently, 3.8 and 3.9 have brought type-only imports/exports, along with ECMAScript features like private fields, top-level await in modules, and new export * syntaxes. These releases also delivered performance and scalability optimizations.

We haven’t even touched on all the work in our language service, our infrastructure, our website, and other core projects which are incredibly valuable to the TypeScript experience. Beyond the core team’s projects is the incredible community of contributors in the ecosystem, pushing the experience forward, and helping out with DefinitelyTyped and even TypeScript itself. DefinitelyTyped had just 80 pull requests in 2012 when it first started, picking up on the tail end of the year. In 2019, it had over 8300 pull requests , which still astounds us. These contributions are fundamental to the TypeScript experience, so we’re grateful for such a bustling and eager community that’s been improving the ecosystem and pushed us to constantly improve.

What’s New?

All this brings us to 4.0! So, without further ado, let’s dive into what’s new!

Variadic Tuple Types

Labeled tuple elements, class property inference from constructors, short-circuiting assignment operators.

  • unknown on catch Clauses

Custom JSX Factories

Speed improvements in build mode with --noemitonerror, --incremental with --noemit, convert to optional chaining, /** @deprecated */ support, partial semantic mode at startup, smarter auto-imports, our new website, breaking changes.

Consider a function in JavaScript called concat that takes two array or tuple types and concatenates them together to make a new array.

Also consider tail , that takes an array or tuple, and returns all elements but the first.

How would we type either of these in TypeScript?

For concat , the only valid thing we could do in older versions of the language was to try and write some overloads.

Uh…okay, that’s…seven overloads for when the second array is always empty. Let’s add some for when arr2 has one argument.

We hope it’s clear that this is getting unreasonable. Unfortunately, you’d also end up with the same sorts of issues typing a function like tail .

This is another case of what we like to call “death by a thousand overloads”, and it doesn’t even solve the problem generally. It only gives correct types for as many overloads as we care to write. If we wanted to make a catch-all case, we’d need an overload like the following:

But that signature doesn’t encode anything about the lengths of the input, or the order of the elements, when using tuples.

TypeScript 4.0 brings two fundamental changes, along with inference improvements, to make typing these possible.

The first change is that spreads in tuple type syntax can now be generic. This means that we can represent higher-order operations on tuples and arrays even when we don’t know the actual types we’re operating over. When generic spreads are instantiated (or, replaced with a real type) in these tuple types, they can produce other sets of array and tuple types.

For example, that means we can type function like tail , without our “death by a thousand overloads” issue.

The second change is that rest elements can occur anywhere in a tuple – not just at the end!

Previously, TypeScript would issue an error like the following:

But with TypeScript 4.0, this restriction is relaxed.

Note that in cases when we spread in a type without a known length, the resulting type becomes unbounded as well, and all the following elements factor into the resulting rest element type.

By combining both of these behaviors together, we can write a single well-typed signature for concat :

While that one signature is still a bit lengthy, it’s just one signature that doesn’t have to be repeated, and it gives predictable behavior on all arrays and tuples.

This functionality on its own is great, but it shines in more sophisticated scenarios too. For example, consider a function to partially apply arguments called partialCall . partialCall takes a function – let’s call it f – along with the initial few arguments that f expects. It then returns a new function that takes any other arguments that f still needs, and calls f when it receives them.

TypeScript 4.0 improves the inference process for rest parameters and rest tuple elements so that we can type this and have it “just work”.

In this case, partialCall understands which parameters it can and can’t initially take, and returns functions that appropriately accept and reject anything left over.

Variadic tuple types enable a lot of new exciting patterns, especially around function composition. We expect we may be able to leverage it to do a better job type-checking JavaScript’s built-in bind method. A handful of other inference improvements and patterns also went into this, and if you’re interested in learning more, you can take a look at the pull request for variadic tuples.

Improving the experience around tuple types and parameter lists is important because it allows us to get strongly typed validation around common JavaScript idioms – really just slicing and dicing argument lists and passing them to other functions. The idea that we can use tuple types for rest parameters is one place where this is crucial.

For example, the following function that uses a tuple type as a rest parameter…

…should appear no different from the following function…

…for any caller of foo .

There is one place where the differences begin to become observable though: readability. In the first example, we have no parameter names for the first and second elements. While these have no impact on type-checking, the lack of labels on tuple positions can make them harder to use – harder to communicate our intent.

That’s why in TypeScript 4.0, tuples types can now provide labels.

To deepen the connection between parameter lists and tuple types, the syntax for rest elements and optional elements mirrors the syntax for parameter lists.

There are a few rules when using labeled tuples. For one, when labeling a tuple element, all other elements in the tuple must also be labeled.

It’s worth noting – labels don’t require us to name our variables differently when destructuring. They’re purely there for documentation and tooling.

Overall, labeled tuples are handy when taking advantage of patterns around tuples and argument lists, along with implementing overloads in a type-safe way. In fact, TypeScript’s editor support will try to display them as overloads when possible.

To learn more, check out the pull request for labeled tuple elements.

TypeScript 4.0 can now use control flow analysis to determine the types of properties in classes when noImplicitAny is enabled.

In cases where not all paths of a constructor assign to an instance member, the property is considered to potentially be undefined .

In cases where you know better (e.g. you have an initialize method of some sort), you’ll still need an explicit type annotation along with a definite assignment assertion ( ! ) if you’re in strictPropertyInitialization .

For more details, see the implementing pull request .

JavaScript, and a lot of other languages, support a set of operators called compound assignment operators. Compound assignment operators apply an operator to two arguments, and then assign the result to the left side. You may have seen these before:

So many operators in JavaScript have a corresponding assignment operator! Up until recently, however, there were three notable exceptions: logical and ( && ), logical or ( || ), and nullish coalescing ( ?? ).

That’s why TypeScript 4.0 supports a new ECMAScript feature to add three new assignment operators: &&= , ||= , and ??= .

These operators are great for substituting any example where a user might write code like the following:

Or a similar if block like

There are even some patterns we’ve seen (or, uh, written ourselves) to lazily initialize values, only if they’ll be needed.

(look, we’re not proud of all the code we write…)

On the rare case that you use getters or setters with side-effects, it’s worth noting that these operators only perform assignments if necessary. In that sense, not only is the right side of the operator “short-circuited” – the assignment itself is too.

Try running the following example to see how that differs from always performing the assignment.

We’d like to extend a big thanks to community member Wenlu Wang for this contribution!

For more details, you can take a look at the pull request here . You can also check out TC39’s proposal repository for this feature .

unknown on catch Clause Bindings

Since the beginning days of TypeScript, catch clause variables have always been typed as any . This meant that TypeScript allowed you to do anything you wanted with them.

The above has some undesirable behavior if we’re trying to prevent more errors from happening in our error-handling code! Because these variables have the type any by default, they lack any type-safety which could have errored on invalid operations.

That’s why TypeScript 4.0 now lets you specify the type of catch clause variables as unknown instead. unknown is safer than any because it reminds us that we need to perform some sorts of type-checks before operating on our values.

While the types of catch variables won’t change by default, we might consider a new --strict mode flag in the future so that users can opt in to this behavior. In the meantime, it should be possible to write a lint rule to force catch variables to have an explicit annotation of either : any or : unknown .

For more details you can peek at the changes for this feature .

When using JSX, a fragment is a type of JSX element that allows us to return multiple child elements. When we first implemented fragments in TypeScript, we didn’t have a great idea about how other libraries would utilize them. Nowadays most other libraries that encourage using JSX and support fragments have a similar API shape.

In TypeScript 4.0, users can customize the fragment factory through the new jsxFragmentFactory option.

As an example, the following tsconfig.json file tells TypeScript to transform JSX in a way compatible with React, but switches each factory invocation to h instead of React.createElement , and uses Fragment instead of React.Fragment .

In cases where you need to have a different JSX factory on a per-file basis, you can take advantage of the new /** @jsxFrag */ pragma comment. For example, the following…

…will get transformed to this output JavaScript…

We’d like to extend a big thanks to community member Noj Vek for sending this pull request and patiently working with our team on it.

You can see that the pull request for more details!

Previously, compiling a program after a previous compile with errors under --incremental would be extremely slow when using the --noEmitOnError flag. This is because none of the information from the last compilation would be cached in a .tsbuildinfo file based on the --noEmitOnError flag.

TypeScript 4.0 changes this which gives a great speed boost in these scenarios, and in turn improves --build mode scenarios (which imply both --incremental and --noEmitOnError ).

For details, read up more on the pull request .

TypeScript 4.0 allows us to use the --noEmit flag when while still leveraging --incremental compiles. This was previously not allowed, as --incremental needs to emit a .tsbuildinfo files; however, the use-case to enable faster incremental builds is important enough to enable for all users.

For more details, you can see the implementing pull request .

Editor Improvements

The TypeScript compiler doesn’t only power the editing experience for TypeScript itself in most major editors – it also powers the JavaScript experience in the Visual Studio family of editors and more. For that reason, much of our work focuses on improving editor scenarios – the place you spend most of your time as a developer.

Using new TypeScript/JavaScript functionality in your editor will differ depending on your editor, but

  • Visual Studio Code supports selecting different versions of TypeScript . Alternatively, there’s the JavaScript/TypeScript Nightly Extension to stay on the bleeding edge (which is typically very stable).
  • Visual Studio 2017/2019 have the SDK installers above and MSBuild installs .
  • Sublime Text 3 supports selecting different versions of TypeScript

You can check out a partial list of editors that have support for TypeScript to learn more about whether your favorite editor has support to use new versions.

Optional chaining is a recent feature that’s received a lot of love. That’s why TypeScript 4.0 brings a new refactoring to convert common patterns to take advantage of optional chaining and nullish coalescing !

Keep in mind that while this refactoring doesn’t perfectly capture the same behavior due to subtleties with truthiness/falsiness in JavaScript, we believe it should capture the intent for most use-cases, especially when TypeScript has more precise knowledge of your types.

For more details, check out the pull request for this feature .

TypeScript’s editing support now recognizes when a declaration has been marked with a /** @deprecated * JSDoc comment. That information is surfaced in completion lists and as a suggestion diagnostic that editors can handle specially. In an editor like VS Code, deprecated values are typically displayed a strike-though style like this .

Some examples of deprecated declarations with strikethrough text in the editor

This new functionality is available thanks to Wenlu Wang . See the pull request for more details.

We’ve heard a lot from users suffering from long startup times, especially on bigger projects. The culprit is usually a process called program construction . This is the process of starting with an initial set of root files, parsing them, finding their dependencies, parsing those dependencies, finding those dependencies’ dependencies, and so on. The bigger your project is, the longer you’ll have to wait before you can get basic editor operations like go-to-definition or quick info.

That’s why we’ve been working on a new mode for editors to provide a partial experience until the full language service experience has loaded up. The core idea is that editors can run a lightweight partial server that only looks at the current files that the editor has open.

It’s hard to say precisely what sorts of improvements you’ll see, but anecdotally, it used to take anywhere between 20 seconds to a minute before TypeScript would become fully responsive on the Visual Studio Code codebase. In contrast, our new partial semantic mode seems to bring that delay down to just a few seconds . As an example, in the following video, you can see two side-by-side editors with TypeScript 3.9 running on the left and TypeScript 4.0 running on the right.

When restarting both editors on a particularly large codebase, the one with TypeScript 3.9 can’t provide completions or quick info at all. On the other hand, the editor with TypeScript 4.0 can immediately give us a rich experience in the current file we’re editing, despite loading the full project in the background.

Currently the only editor that supports this mode is Visual Studio Code which has some UX improvements coming up in Visual Studio Code Insiders . We recognize that this experience may still have room for polish in UX and functionality, and we have a list of improvements in mind. We’re looking for more feedback on what you think might be useful.

For more information, you can see the original proposal , the implementing pull request , along with the follow-up meta issue .

Auto-import is a fantastic feature that makes coding a lot easier; however, every time auto-import doesn’t seem to work, it can throw users off a lot. One specific issue that we heard from users was that auto-imports didn’t work on dependencies that were written in TypeScript – that is, until they wrote at least one explicit import somewhere else in their project.

Why would auto-imports work for @types packages, but not for packages that ship their own types? It turns out that auto-imports only work on packages your project already includes. Because TypeScript has some quirky defaults that automatically add packages in node_modules/@types to your project, those packages would be auto-imported. On the other hand, other packages were excluded because crawling through all your node_modules packages can be really expensive.

All of this leads to a pretty lousy getting started experience for when you’re trying to auto-import something that you’ve just installed but haven’t used yet.

TypeScript 4.0 now does a little extra work in editor scenarios to include the packages you’ve listed in your package.json ‘s dependencies (and peerDependencies ) fields. The information from these packages is only used to improve auto-imports, and doesn’t change anything else like type-checking. This allows us to provide auto-imports for all of your dependencies that have types, without incurring the cost of a complete node_modules search.

In the rare cases when your package.json lists more than ten typed dependencies that haven’t been imported yet, this feature automatically disables itself to prevent slow project loading. To force the feature to work, or to disable it entirely, you should be able to configure your editor. For Visual Studio Code, this is the “Include Package JSON Auto Imports” (or typescript.preferences.includePackageJsonAutoImports ) setting.

Configuring 'include package JSON auto imports'

The TypeScript website has recently been rewritten from the ground up and rolled out!

A screenshot of the new TypeScript website

We already wrote a bit about our new site , so you can read up more there; but it’s worth mentioning that we’re still looking to hear what you think! If you have questions, comments, or suggestions, you can file them over on the website’s issue tracker .

lib.d.ts Changes

Our lib.d.ts declarations have changed – most specifically, types for the DOM have changed. The most notable change may be the removal of document.origin which only worked in old versions of IE and Safari MDN recommends moving to self.origin .

Properties Overriding Accessors (and vice versa) is an Error

Previously, it was only an error for properties to override accessors, or accessors to override properties, when using useDefineForClassFields ; however, TypeScript now always issues an error when declaring a property in a derived class that would override a getter or setter in the base class.

See more details on the implementing pull request .

Operands for delete must be optional.

When using the delete operator in strictNullChecks , the operand must now be any , unknown , never , or be optional (in that it contains undefined in the type). Otherwise, use of the delete operator is an error.

Usage of TypeScript’s Node Factory is Deprecated

Today TypeScript provides a set of “factory” functions for producing AST Nodes; however, TypeScript 4.0 provides a new node factory API. As a result, for TypeScript 4.0 we’ve made the decision to deprecate these older functions in favor of the new ones.

For more details, read up on the relevant pull request for this change .

What’s Next?

You’ve reached the end of this release post, but luckily there’s more coming. TypeScript 4.1’s iteration plan is already up so you can get a sense of what’s on the horizon. In the meantime, you can give new features in 4.1 a shot by using nightly builds in your workspace , or maybe just in your editor . Whether you’re on TypeScript 4.0, or the next version, we’re interested in hearing feedback! Feel free to leave a comment below, reach out over Twitter , or file an issue on GitHub .

We said it once, and we’ll say it again: we owe so much to our community for all their work and dedication. In turn, we want to making coding in TypeScript and JavaScript the pure joy you deserve. This involves not just focusing on one thing, but a combination of improving the language and editing experience, keeping an eye on speed, iterating on our UX, smoothing the onboarding and learning experience as a whole, and more.

Thank you so much, and enjoy 4.0!

Happy Hacking!

– Daniel Rosenwasser and the TypeScript Team

assignment operators typescript

Daniel Rosenwasser Senior Program Manager, TypeScript

assignment operators typescript

Discussion is closed. Login to edit/delete existing comments.

Are there any college-level textbooks on programming with TypeScript or do any universities offer programming courses using this language? It seems like a nice language to use as an introduction to programming.

From MDN https://developer.mozilla.org/zh-CN/docs/Web/API/Document/origin , document.origin only used in Chrome 41. and It may be removed in some newer version.

light-theme-icon

Tutlane Logo

TypeScript Operators

In typescript, operator is a programming element or symbol that specifies what kind of an operation can be performed on operands or variables. For example, an addition (+) operator in typescript is useful to perform sum operation on operands.

In typescript, we have a different type of operators available, those are:

  • Arithmetic Operators
  • Relational Operators
  • Logical Operators
  • Bitwise Operators
  • Assignment Operators
  • Conditional Operators
  • TypeScript Arithmetic Operators

In TypeScript, arithmetic operators are useful to perform the mathematical operations like addition (+), subtraction (-), multiplication (*), division (/), etc. based on our requirements.

For example, we have two variables x = 100 , y = 50 and we can perform arithmetic operations on these variables like as following.

let x: number = 100;

let y: number = 50;

console.log( 'Addition:' , x + y);

console.log( 'Substraction:' , x - y);

console.log( 'Multiplcation:' , x * y);

console.log( 'Division:' , x / y);

When we compile and execute the above typescript program, we will get the result like as below.

Addition: 150

Substraction: 50

Multiplcation: 5000

Division: 2

Following table lists the different type of operators available in typescript arithmetic operators.

  • TypeScript Relational Operators

In typescript, Relational Operators are useful to check the relation between two operands like we can determine whether two operand values equal or not, etc. based on our requirements.

For example, we have two variables x = 100 , y = 200 and we can perform comparison (relational) operations on these variables like as following.

let x = 100, y = 200;

if (x == y) {

    console.log( 'Both are equal' );

if (x != y) {

    console.log( 'Both are not equal' );

if (x > y) {

    console.log( 'x is greater than y' );

if (x < y) {

    console.log( 'x is less than y' );

if (x >= y) {

    console.log( 'x is greater than or equal to y' );

if (x <= y) {

    console.log( 'x is less than or equal to y' );

When we compile and execute the above typescript program, we will get the result as below.

Both are not equal

x is less than y

x is less than or equal to y

Following table lists the different type of operators available in typescript relational operators.

  • TypeScript Logical Operators

In typescript, Logical Operators are useful to perform the logical operation between two operands like AND, OR and NOT based on our requirements. 

The Logical Operators will always work with Boolean expressions ( true or false ) and return Boolean values.

Following is the example of performing the logical operations on required variables in typescript.

var x: boolean = true , y: boolean = false ;

var result: boolean ;

// AND Operator

result = x && y;

console.log( 'AND Operator: ' , result);

// OR Operator

result = x || y;

console.log( 'OR Operator: ' , result);

// NOT Operator

result = !x;

console.log( 'NOT Operator: ' , result);

AND Operator:  false

OR Operator:  true

NOT Operator:  false

Following table lists the different type of operators available in typescript logical operators.

  • TypeScript Bitwise Operators

In typescript, the Bitwise Operators will work on bits and these are useful to perform a bit by bit operations on operands.

For example, we have variables x = 10 , y = 20 and the binary format of these variables will be like as shown below.

x = 10 (00001010)

y = 20 (00010100)

When we apply Bitwise OR (|) operator on these parameters we will get the result like as shown below.

-----------

00011110 = 30

Following table lists the different type of operators available in typescript bitwise operators.

  • TypeScript Assignment Operators

In typescript, the Assignment Operators are useful to assign a new value to the operand and these operators will work with only one operand.

For example, we can declare and assign a value to the variable using assignment operator (=) like as shown below.

let x: number = 20;

console.log( "Add Assignment: " , x);

console.log( "Modulo Assignment: " , x);

console.log( "Multiply Assignment: " , x);

console.log( "Division Assignment: " , x);

console.log( "Subtract Assignment: " , x);

Add Assignment:  30

Modulo Assignment:  2

Multiply Assignment:  20

Division Assignment:  2

Subtract Assignment:  -8

Following table lists the different type of operators available in typescript assignment operators. 

TypeScript Miscellaneous Operators

Same like, arithmetic, comparison, etc. we have other miscellaneous operators available in typescript, those are:

  • Concatenation operator (+)
  • Conditional Operator (?)
  • Type Operators

We will learn about these operators in next typescript chapters.

Table of Contents

  • TypeScript Operators with Examples

Logical assignment operators in Typescript

Portrait of Tom

Hi there, Tom here! As of writing, Typescript 4's stable release is imminent (August 2020) and with it are some very nice changes to come.

Typescript 4 ahead

One of those is the addition of logical assignment operators, which allow to use the logical operators with an assignment. As a reminder, here are the logical operators being used for the new logical assignment operators:

These new logical assignment operators themselves are part of the collection of compound assignment operators , which apply an operator to two arguments and then assign the result to the left side. They are available in many languages and now get enhanced in Typescript.

Code, please!

What does that mean? You probably already know a few compound assignment operators:

The new logical assignment operators now give you the ability to use your logical operator of choice for the same kind of assignment:

Note that these new operators were already available in JS and are also natively suppported by V8.

And that’s about it for one of Typescript 4’s great new features. Thanks for the quick read and I hope you could learn something!

expressFlow is now Lean-Forge

TypeScript Tutorial

  • TypeScript Tutorial
  • TypeScript - Home
  • TypeScript - Overview
  • TypeScript - Environment Setup
  • TypeScript - Basic Syntax
  • TypeScript - Types
  • TypeScript - Variables
  • TypeScript - Operators
  • TypeScript - Decision Making
  • TypeScript - Loops
  • TypeScript - Functions
  • TypeScript - Numbers
  • TypeScript - Strings
  • TypeScript - Arrays
  • TypeScript - Tuples
  • TypeScript - Union
  • TypeScript - Interfaces
  • TypeScript - Classes
  • TypeScript - Objects
  • TypeScript - Namespaces
  • TypeScript - Modules
  • TypeScript - Ambients
  • TypeScript Useful Resources
  • TypeScript - Quick Guide
  • TypeScript - Useful Resources
  • TypeScript - Discussion
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

TypeScript - Assignment Operators Examples

Note − Same logic applies to Bitwise operators, so they will become <<=, >>=, >>=, &=, |= and ^=.

On compiling, it will generate the following JavaScript code −

It will produce the following output −

To Continue Learning Please Login

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free

Nullish coalescing assignment (??=)

The nullish coalescing assignment ( ??= ) operator, also known as the logical nullish assignment operator, only evaluates the right operand and assigns to the left if the left operand is nullish ( null or undefined ).

Description

Nullish coalescing assignment short-circuits , meaning that x ??= y is equivalent to x ?? (x = y) , except that the expression x is only evaluated once.

No assignment is performed if the left-hand side is not nullish, due to short-circuiting of the nullish coalescing operator. For example, the following does not throw an error, despite x being const :

Neither would the following trigger the setter:

In fact, if x is not nullish, y is not evaluated at all.

Using nullish coalescing assignment

You can use the nullish coalescing assignment operator to apply default values to object properties. Compared to using destructuring and default values , ??= also applies the default value if the property has value null .

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Nullish coalescing operator ( ?? )

TypeScript Operators: Learn Bitwise, Assignment, and Comma Operators with Examples

  • Mar 6, 2024

TypeScript Operators: Learn Bitwise, Assignment, and Comma Operators with Examples

# TypeScript Bitwise Operators

Bitwise operators are used for evaluating bit-based operations. Sometimes, when we need to manipulate bits of integer values, we utilize bitwise operators .

These operators, similar to many programming languages, work with 32 bits of an integer and operate on binary operands.

Where Operand1 and Operand2 are JavaScript expressions, and Operators are bitwise operators.

Let’s assume the values of A and B are 5 and 10, and observe the results:

Following is a Bitwise operators Example .

# TypeScript Assignment Operators

Assignment operators perform operations and assign values from left to right.

The following table explains it with examples.

| Operator | Title | Description| Example| | :------- | :--------------------------- | ------------------ | ---------------- | ------------------ | | = | Simple assign | Evaluates, And operation on bits Integers parameters | a=2 and value of a is 2 | | += | Add And assign | Add right operand to left and assign the result to left operand | a+=2 and value of a is equal to a=a+2 | | -= | Subtract and assign | Subtract right operand to left and assign the result to left operand | a-=2 and value of a is equal to a=a+2 | | *= | Multiply And assign | Multiply right operand with left and assign the result to left operand | a*a=2 is equal to a=a*2 | | /= | Divide and assign | Divide right operand with left and assign the result to left operand | c/=2 is equal to c=c/2 | | %= | Modulus And Assign | Divide right operand with left and assign the result of the remainder to left operand | c%=2 is equal to c=c%2 | | <<= | Left Shifts And assign | Perform left shift and result is assigned to left operand | c<<=2 is equal to c=c<<2 | | >>= | Right Shifts And assign | Perform Right shift and result is assigned to left operand | c>>=2 is equal to c=c>>2 | | &= | Bitwise And Assign | Perform Bitwise And and the result is assigned to left operand | c&=2 is equal to c=c&2 | | ^= | Bitwise Exclusive And Assign | Perform Bitwise Exclusive OR and result is assigned to left operand | c^=2 is equal to c=c^2 | | \|= | Bitwise Or And Assign | Perform Bitwise inclusive OR and the result is assigned to left operand | c | =2 is equal to c=c | 2 |

# TypeScript Comma Operator

The comma operator ( , ) is used to perform multiple expressions and return the value of the last expression. Expressions are evaluated from left to right.

Here is an example Example

# Conclusion

In conclusion, you’ve learned about TypeScript operators with examples, including bitwise operators, assignment operators, and the comma operator.

  • #Typescript

Short Circuiting Assignment Operators in Typescript 4.0 & Angular 11

Using Short Circuiting Assignment Operators in Angular

Angular 11 supports only Typescript 4.0 version .

Typescript 4.0 has some cool features that can be used in Angular 11. 

One such feature is short-circuiting assignment operators .

JavaScript and other languages, supports compound assignment operators .

Compound-assignment operators perform the operation specified by the additional operator, then assign the result to the left operand as shown below.

But we cannot use logical and (&&), logical or (||), and nullish coalescing (??) operators for compound assignment.

Typescript 4.0 supports now these three operators for compound assignment.

We can replace the above statment with single line logical OR compound assignment a ||= b .

With this shorthand notation we can lazily initialize values, only if they needed.

The logical assignment operators work differently when compare to other mathematical assignment operators.

Mathematical assignment operators always trigger a set operation.

But logical assignment operators uses its short-circuiting semantics and avoids set operation if possible.

We won’t be getting much performance benefit, but calling set operation unnecessarily has it’s side effects.

In the following example, if the.innerHTML setter was invoked unnecessarily, it might result in the loss of state (such as focus) that is not serialized in HTML:

Arunkumar Gudelli

COMMENTS

  1. TypeScript: Playground Example

    Logical Operators and Assignment. Logical Operators and Assignment are new features in JavaScript for 2020. These are a suite of new operators which edit a JavaScript object. Their goal is to re-use the concept of mathematical operators (e.g. += -= *=) but with logic instead. interface User {. id?: number.

  2. TypeScript Operators

    In this article, we are going to learn various types of TypeScript Operators. Below are the different TypeScript Operators: Table of Content. TypeScript Arithmetic operators. TypeScript Logical operators. TypeScript Relational operators. TypeScript Bitwise operators. TypeScript Assignment operators.

  3. Assignment Operators in TypeScript

    TypeScript Tutorial. An assignment operator requires two operands. The value of the right operand is assigned to the left operand. The sign = denotes the simple assignment operator. The typescript also has several compound assignment operators, which is actually shorthand for other operators. List of all such operators are listed below.

  4. TypeScript: Documentation

    That's why in TypeScript 4.0, tuples types can now provide labels. type Range = [start: number, end: number]; To deepen the connection between parameter lists and tuple types, the syntax for rest elements and optional elements mirrors the syntax for parameter lists.

  5. Understanding TypeScript Operators

    Introduction Understanding TypeScript operators is a fundamental part of learning TypeScript. TypeScript operators are symbols used to perform operations on operands. An operand can be a variable, a value, or a literal. Types of TypeScript Operators There are various types of operators in TypeScript: Arithmetic Operators; Logical Operators

  6. Getting To Know Typescript Operators In Depth

    Basics Of Typescript Operators. 🧷. Operators in Typescript are symbols used to perform specific operations on one or more operands. They are the building blocks that allow us to create logic within our Typescript applications. Arithmetic Operators. Logical Operators. Bitwise Operators. Relational Operators. Assignment Operators.

  7. Assignment Operators in TypeScript

    TypeScript assignment operators, including the basic assignment (=) and compound assignments (+=, -=, *=, /=, %=), provide a concise way to assign values and perform compound operations on variables. These operators enhance code readability and efficiency by combining assignment with arithmetic or modulus operations in a single step.

  8. TypeScript Tutorial

    This video is about Assignment Operators which are generally used in TypeScript.đź”´TypeScript Tutorial : Beginner to Advancedđź”´https://www.youtube.com/watch?v...

  9. TypeScript Operators Tutorial

    TypeScript Operators Tutorial. In this TypeScript tutorial we learn the standard arithmetic, assignment, comparison (relational) and logical (conditional) operators. We also discuss the negation, concatenation, typeof and ternary operators as well as operator precedence in TypeScript. What are operators. Arithmetic operators. Assignment operators.

  10. Announcing TypeScript 4.0

    TypeScript 4.0 can now use control flow analysis to determine the types of properties in classes when noImplicitAny is enabled. class Square {// Previously: ... Compound assignment operators apply an operator to two arguments, and then assign the result to the left side. You may have seen these before:

  11. Typescript literal types and addition assignment operators

    2) d = d + b; This expression will be interpreted by the compiler as following: Assignment Expression: left side: d. token (operator): =. right side: d + b. In order to check the types on both sides, the compiler deducts the type for the right and left expression. In case of the left side its simple. For the right side it will be number.

  12. TypeScript Operators

    TypeScript Assignment Operators In typescript, the Assignment Operators are useful to assign a new value to the operand and these operators will work with only one operand. For example, we can declare and assign a value to the variable using assignment operator (=) like as shown below.

  13. Typescript 4 enhances the compound assignment operators

    Hi there, Tom here! As of writing, Typescript 4's stable release is imminent (August 2020) and with it are some very nice changes to come. Typescript 4 ahead. One of those is the addition of logical assignment operators, which allow to use the logical operators with an assignment. As a reminder, here are the logical operators being used for the ...

  14. Logical OR assignment (||=)

    Description. Logical OR assignment short-circuits, meaning that x ||= y is equivalent to x || (x = y), except that the expression x is only evaluated once. No assignment is performed if the left-hand side is not falsy, due to short-circuiting of the logical OR operator. For example, the following does not throw an error, despite x being const: js.

  15. TypeScript

    Operator. Description. Example. = (Simple Assignment) Assigns values from the right side operand to the left side operand. C = A + B will assign the value of A + B into C. += (Add and Assignment) It adds the right operand to the left operand and assigns the result to the left operand. C += A is equivalent to C = C + A.

  16. Bitwise Operators in Typescript

    Bitwise operators & Binary numbers. Bitwise operators operate on Binary numbers, i.e., zeros & ones. Hence it is essential to understand how they are stored to understand the Bitwise operators. A binary number is a number expressed in the base-2 numeral system or binary numeral system. It uses 0 (zero) and 1 (one) to represent the numbers.

  17. Nullish coalescing assignment (??=)

    No assignment is performed if the left-hand side is not nullish, due to short-circuiting of the nullish coalescing operator. For example, the following does not throw an error, despite x being const :

  18. TypeScript Operators: Learn Bitwise, Assignment, and Comma Operators

    Bitwise operators are used for evaluating bit-based operations. Sometimes, when we need to manipulate bits of integer values, we utilize bitwise operators . These operators, similar to many programming languages, work with 32 bits of an integer and operate on binary operands.

  19. typescript

    I don't find two this.xs being redundant in that specific syntax, as there are two operators, and both of the operators need their operands. The case just happens to use the same variable in the operands of both of the operators. If the case was const x = (y) ? 1 : 2;, you wouldn't think 1 was redundant. For what you're after, we'd need a brand ...

  20. Short Circuiting Assignment Operators in Typescript 4.0 & Angular 11

    Typescript 4.0 has some cool features that can be used in Angular 11. One such feature is short-circuiting assignment operators. JavaScript and other languages, supports compound assignment operators. Compound-assignment operators perform the operation specified by the additional operator, then assign the result to the left operand as shown below.

  21. Assignment Operators in TypeScript

    Assignment Operators in TypeScript . Assignment operators are used to assign values to variables. This type of statement consists of a variable name, an assignment operator, and an expression. When appropriate, you can declare a variable and assign a value to it in a single statement. In assignment expressions, the right-hand expression is ...