Logo

TypeScript Deep Dive

Destructuring.

TypeScript supports the following forms of Destructuring (literally named after de-structuring i.e. breaking up the structure):

Object Destructuring

Array destructuring.

It is easy to think of destructuring as an inverse of structuring . The method of structuring in JavaScript is the object literal:

Without the awesome structuring support built into JavaScript, creating new objects on the fly would indeed be very cumbersome. Destructuring brings the same level of convenience to getting data out of a structure.

Destructuring is useful because it allows you to do in a single line, what would otherwise require multiple lines. Consider the following case:

Here in the absence of destructuring you would have to pick off x,y,width,height one by one from rect .

To assign an extracted variable to a new variable name you can do the following:

Additionally you can get deep data out of a structure using destructuring. This is shown in the following example:

Object Destructuring with rest

You can pick up any number of elements from an object and get an object of the remaining elements using object destructuring with rest.

A common use case is also to ignore certain properties. For example:

A common programming question: "How to swap two variables without using a third one?". The TypeScript solution:

Note that array destructuring is effectively the compiler doing the [0], [1], ... and so on for you. There is no guarantee that these values will exist.

Array Destructuring with rest

You can pick up any number of elements from an array and get an array of the remaining elements using array destructuring with rest.

Array Destructuring with ignores

You can ignore any index by simply leaving its location empty i.e. , , in the left hand side of the assignment. For example:

JS Generation

The JavaScript generation for non ES6 targets simply involves creating temporary variables, just like you would have to do yourself without native language support for destructuring e.g.

Destructuring can make your code more readable and maintainable by reducing the line count and making the intent clear. Array destructuring can allow you to use arrays as though they were tuples.

Last updated 4 years ago

  • Return Multiple values from a Function in TypeScript

avatar

Last updated: Feb 27, 2024 Reading time · 5 min

banner

# Table of Contents

  • Define a Function with multiple return Types in TypeScript

# Return Multiple values from a Function in TypeScript

To return multiple values from a function in TypeScript, group the values in an array and return the array, e.g. return [myValue1, myValue2] as const .

You can then destructure and use the values the function returns.

return multiple values from function

If you need to define a function with multiple return types, click on the following subheading:

We declared a function that returns multiple values by grouping them in an array.

Notice that the type of the result variable (and the function's return type) is ["bobbyhadz.com", 100] .

The as const syntax is called a const assertion in TypeScript.

The const assertion sets the function's return type to be readonly ["bobbyhadz.com", 100] , which is exactly what we want.

Let's look at the function's return type if we omit the const assertion.

Without the as const syntax, the function is typed to return an array containing strings or numbers.

This isn't great, because when we destructure the values from the array into the str and num variables, they are typed as string | number .

The string | number syntax is called a union type in TypeScript. A union type is formed by combining two or more other types.

I've written a detailed article on how to define an array with multiple types in TS .

# Using a tuple return type instead

You could get around this by explicitly setting the function's return type to a tuple containing a string and a number .

using tuple return type instead

We've explicitly typed the function to return a tuple where the first element is a string and the second is a number.

The syntax with the square brackets on the left-hand side of the assignment is called destructuring.

An easy way to think about it is that we are assigning the elements of the array to variables. Note that the order of assignment and the order of the values in the array is the same.

If you don't want to use destructuring, you can explicitly access the values by using bracket notation.

# Define a Function with multiple return Types in TypeScript

Use a union type to define a function with multiple return types in TypeScript.

defining function with multiple return types

The function must return a value that is represented in the union type, otherwise, the type checker throws an error.

# Using arrow functions

You can use the same approach when working with arrow functions.

You can include as many types as necessary in your union. Simply separate the types with a pipe | .

The function in the example above returns a string or number .

# Using classes, type aliases or interfaces

The same approach can be used with type aliases , interfaces or classes.

Here is an example of a function that returns a string array or a numeric array.

# Use a type guard before accessing properties

The functions in the examples have multiple return types, so we have to use a type guard before accessing type-specific methods or properties.

The result variable stores a string or a number , so TypeScript won't allow us to access a string-specific built-in method like toUpperCase until we can narrow the type down.

The type of the value stored in result is a string in the if block.

How you narrow the type down might be different depending on the type of the values the function returns.

For example, if you had to check for an array , you'd use Array.isArray(myArray) and if you had to check if a value is an instance of a specific class, you'd use myInstance instanceof myClass .

# Using a type assertion

A quick and dirty way to get around having to check the type is to use a type assertion .

The as keyword is a type assertion and sets the type of the result variable to string without us having to use a type guard.

This approach should generally be avoided as it isn't type-safe and would cause a runtime error if the result variable stored a number .

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • Declare functions returning Object or Array in TypeScript
  • Declare a function with a Promise return type in TypeScript
  • How to Declare a Function that throws an Error in TypeScript
  • (instanceof) 'X' Only refers to a type, but is being used as a value here

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

typescript multiple assignment

0:02 We've got a tricky problem here. We're using an interface user as a way to represent the user within our system. We've got a function down here called getUserId, which takes in a user and returns its ID.

0:17 Now, this getUserId (defaultUser) is failing. It's failing because this defaultUser is not meeting this user contract. If I were to change it...I would say id, 1, firstName, Matt, lastName, Pocock, isAdmin, true, then it's going to pass.

0:43 I don't want the error to be down here. I ideally want the error to be at this line or around here, because I want to make sure that my defaultUser is matching that user contract. Your job is to go through the TypeScript docs and work out how you would do this.

Assigning Types to Variables self.__wrap_balancer=(t,e,n)=>{n=n||document.querySelector(`[data-br="${t}"]`);let o=n.parentElement,r=E=>n.style.maxWidth=E+"px";n.style.maxWidth="";let i=o.clientWidth,s=o.clientHeight,c=i/2,u=i,d;if(i){for(;c+1

Here we have an interface that represents a user within our system:

There's a function called getUserId that takes in a user, and returns its id.

Our test is currently failing, becaus

typescript multiple assignment

typescript multiple assignment

Home » Introduction and Basics » Type assignment in typescript

Type assignment in typescript

Type assignment in typescript.

TypeScript is a statically typed superset of JavaScript that adds optional type annotations to the language. This allows developers to catch errors and bugs at compile-time rather than runtime. One of the key features of TypeScript is its ability to assign types to variables, functions, and objects. In this article, we will explore the different ways to assign types in TypeScript and provide examples to illustrate their usage.

Basic Type Assignment

The most straightforward way to assign a type in TypeScript is by using the colon (:) syntax. This syntax is used to declare the type of a variable, function parameter, or function return value. Let’s take a look at some examples:

In the above examples, we have assigned the type “string” to the variable “name”, the type “string” to the function parameter “person”, and the type “number” to the function parameters “a” and “b” as well as the return value of the function “add”. This ensures that the assigned values or function arguments are of the specified type, and any type mismatches will result in a compile-time error.

Implicit Type Assignment

In addition to explicit type assignment, TypeScript also supports implicit type assignment. This means that TypeScript can infer the type of a variable based on its initial value. Let’s see an example:

In the above example, we have declared a variable “age” without explicitly assigning a type. TypeScript infers the type of “age” as “number” based on its initial value of 25. This allows us to write more concise code without sacrificing type safety.

Union Types

Another powerful feature of TypeScript is the ability to assign multiple types to a variable using union types. Union types are denoted by the pipe (|) symbol. Let’s consider an example:

In the above example, we have declared a variable “result” with a union type of “string” and “number”. This means that “result” can hold values of either type. We can assign a string value or a number value to “result” without any compile-time errors. This flexibility allows us to handle different types of data in a single variable.

Type Assertion

Sometimes, TypeScript may not be able to infer the correct type or we may want to override the inferred type. In such cases, we can use type assertion to explicitly specify the type of a value. Type assertion is done using the angle bracket (<>) syntax or the “as” keyword. Let’s see an example:

In the above example, we have a variable “message” with the type “any”. We want to access the “length” property of “message”, which is only available for strings. By using type assertion, we explicitly tell TypeScript that “message” is of type “string” and then access its “length” property. This allows us to perform type-specific operations on values with a broader type.

Type assignment is a fundamental aspect of TypeScript that enables developers to write safer and more maintainable code. By assigning types to variables, function parameters, and return values, we can catch errors at compile-time and improve the overall quality of our code. Additionally, TypeScript provides features like implicit type assignment, union types, and type assertion to enhance flexibility and expressiveness. Understanding and utilizing these type assignment techniques will greatly benefit TypeScript developers in their day-to-day programming tasks.

  • No Comments
  • assignment , typescript

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

Table of Contents

Not stay with the doubts.

Typescript SOS

  • Privacy Overview
  • Strictly Necessary Cookies

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

If you disable this cookie, we will not be able to save your preferences. This means that every time you visit this website you will need to enable or disable cookies again.

Marius Schulz

Nullish Coalescing: The ?? Operator in TypeScript

TypeScript 3.7 added support for the ?? operator, which is known as the nullish coalescing operator . We can use this operator to provide a fallback value for a value that might be null or undefined .

# Truthy and Falsy Values in JavaScript

Before we dive into the ?? operator, let's recall that JavaScript values can either be truthy or falsy : when coerced to a Boolean, a value can either produce the value true or false . In JavaScript, the following values are considered to be falsy:

All other JavaScript values will produce the value true when coerced to a Boolean and are thus considered truthy.

# Providing Fallback Values with the ?? Operator

The ?? operator can be used to provide a fallback value in case another value is null or undefined . It takes two operands and is written like this:

If the left operand is null or undefined , the ?? expression evaluates to the right operand:

Otherwise, the ?? expression evaluates to the left operand:

Notice that all left operands above are falsy values. If we had used the || operator instead of the ?? operator, all of these expressions would've evaluated to their respective right operands:

This behavior is why you shouldn't use the || operator to provide a fallback value for a nullable value. For falsy values, the result might not be the one you wanted or expected. Consider this example:

The expression options.prettyPrint ?? true lets us provide the default value true in case that the prettyPrint property contains the value null or undefined . If prettyPrint contains the value false , the expression false ?? true still evaluates to false , which is exactly the behavior we want here.

Note that using the || operator here would lead to incorrect results. options.prettyPrint || true would evaluate to true for the values null and undefined , but also for the value false . This would clearly not be intended. I've seen this happen in practice a handful of times, so make sure to keep this case in mind and use towards the ?? operator instead.

# Compiled Output: ES2020 and Newer

The nullish coalescing operator has reached Stage 4 ("Finished") of the TC39 process and is now officially part of ES2020 . Therefore, the TypeScript compiler will emit the ?? operator as is without any downleveling when you're targeting "ES2020" (or a newer language version) or "ESNext" in your tsconfig.json file:

So, this simple expression will be emitted unchanged:

If you're planning on using the ?? operator while targeting "ES2020" or a newer language version, head over to caniuse.com and node.green and make sure that all the JavaScript engines you need to support have implemented the operator.

# Compiled JavaScript Output: ES2019 and Older

If you're targeting "ES2019" or an older language version in your tsconfig.json file, the TypeScript compiler will rewrite the nullish coalescing operator into a conditional expression. That way, we can start using the ?? operator in our code today and still have the compiled code successfully parse and execute in older JavaScript engines.

Let's look at the same simple ?? expression again:

Assuming we're targeting "ES2019" or a lower language version, the TypeScript compiler will emit the following JavaScript code:

The value variable is compared against both null and undefined (the result of the expression void 0 ). If both comparisons produce the value false , the entire expression evaluates to value ; otherwise, it evaluates to fallbackValue .

Now, let's look at a slightly more complex example. Instead of a simple value variable, we're going to use a getValue() call expression as the left operand of the ?? operator:

In this case, the compiler will emit the following JavaScript code (modulo whitespace differences):

You can see that the compiler generated an intermediate variable _a to store the return value of the getValue() call. The _a variable is then compared against null and void 0 and (potentially) used as the resulting value of the entire expression. This intermediate variable is necessary so that the getValue function is only called once.

# Compiled Output: Checking for null and undefined

You might be wondering why the compiler emits the following expression to check the value variable against null and undefined :

Couldn't the compiler emit the following shorter check instead?

Unfortunately, it can't do that without sacrificing correctness. For almost all values in JavaScript, the comparison value == null is equivalent to value === null || value === undefined . For those values, the negation value != null is equivalent to value !== null && value !== undefined . However, there is one value for which these two checks aren't equivalent, and that value is document.all :

The value document.all is not considered to be strictly equal to either null or undefined , but it is considered to be loosely equal to both null and undefined . Because of this anomaly, the TypeScript compiler can't emit value != null as a check because it would produce incorrect results for document.all .

You can read more about this curious behavior in an answer to the Why is document.all falsy? question on Stack Overflow. Oh, the things we do for web compatibility.

This article and 44 others are part of the TypeScript Evolution series. Have a look!

logo

  • Web Application
  • My Portfolio

book

The Most Useful GIT Commands

Get a FREE cheat sheet ( value of 8.99$ ) with the most useful GIT commands.

How To Add Multiple Constructors In TypeScript?

Tim Mouskhelichvili

If you come from a C# background, you may want to add multiple constructors to a TypeScript class . Although TypeScript doesn't support multiple constructors, you can still achieve similar behavior.

In TypeScript, you can achieve a similar behavior  to adding multiple constructors by:

  • Adding constructor overloads AND implementing a custom type guard.
  • Using the static factory method to construct a class.
  • Adding a partial class argument to the constructor .

This article explains those solutions with code examples.

Let's get to it 😎.

typescript multiple assignment

Here are some other  TypeScript tutorials  for you to enjoy:

  • Create a global variable in TypeScript
  • Create a queue in TypeScript
  • How to use the yield keyword in TypeScript

Advisory boards aren’t only for executives. Join the LogRocket Content Advisory Board today →

LogRocket blog logo

  • Product Management
  • Solve User-Reported Issues
  • Find Issues Faster
  • Optimize Conversion and Adoption
  • Start Monitoring for Free

A guide to async/await in TypeScript

typescript multiple assignment

Editor’s note : This article was last updated by Oyinkansola Awosan on 15 February 2024 to include information about error handling with try/catch blocks and higher-order functions, as well as to feature TypeScript’s Awaited type.

A Guide To Async/Await In TypeScript

If you’re reading this blog, you probably have some familiarity with asynchronous programming in JavaScript, and you may be wondering how it works in TypeScript.

Asynchronous programming is a way of writing code that can carry out tasks independently of each other, not needing one task to be completed before another gets started. When you think of asynchronous programming, think of multitasking and effective time management.

Introduction to async/await in TypeScript

TypeScript is a superset of JavaScript, so async/await works the same, but with some extra goodies and type safety. TypeScript enables you to ensure type safety for the expected result and even check for type errors, which helps you detect bugs earlier in the development process.

async/await is essentially a syntactic sugar for promises, which is to say that the async/await keyword is a wrapper over promises. An async function always returns a promise. Even if you omit the Promise keyword, the compiler will wrap your function in an immediately resolved promise.

Here’s an example:

Although they look different, the code snippets above are more or less equivalent.

async/await simply enables you to write the code more synchronously and unwraps the promise within the same line of code for you. This is powerful when you’re dealing with complex asynchronous patterns.

To get the most out of the async/await syntax, you’ll need a basic understanding of promises.

What is a promise in TypeScript?

In JavaScript, a “promise” refers to the expectation that something will happen at a particular time, enabling your app to use the result of that future event to perform certain other tasks.

To demonstrate what I mean, I’ll break down a real-world example and translate it into pseudocode, followed by the actual TypeScript code.

Let’s say I have a lawn to mow. I contact a mowing company that promises to mow my lawn in a couple of hours. In turn, I promise to pay them immediately afterward, provided the lawn is properly mowed.

Can you spot the pattern? The first obvious thing to note is that the second event relies entirely on the previous one. If the first event’s promise is fulfilled, the next event’s will be executed. The promise in that event is then either fulfilled, rejected, or remains pending.

typescript multiple assignment

Over 200k developers use LogRocket to create better digital experiences

typescript multiple assignment

Let’s look at this sequence step by step and then explore its code:

Diagram Showing a Promise Sequence in TypeScript

The promise syntax

Before we write out the full code, it makes sense to examine the syntax for a promise — specifically, an example of a promise that resolves into a string.

We declared a promise with the new + Promise keyword, which takes in the resolve and reject arguments. Now let’s write a promise for the flow chart above:

In the code above, we declared both the company’s promises and our promises. The company promise is either resolved after 100,000ms or rejected. A Promise is always in one of three states: resolved if there is no error, rejected if an error is encountered, or pending if the promise has been neither rejected nor fulfilled. In our case, it falls within the 100000ms period.

But how can we execute the task sequentially and synchronously? That’s where the then keyword comes in. Without it, the functions simply run in the order in which they resolve.

Sequential execution with .then

Now we can chain the promises, which allows them to run in sequence with .then . This functions like a normal human language — do this and then that and then that, and so on.

The code below will run the angelMowersPromise . If there is no error, it’ll run the myPaymentPromise . If there is an error in either of the two promises, it’ll be caught in the catch block:

Now let’s look at a more technical example. A common task in frontend programming is to make network requests and respond to the results accordingly.

Below is a request to fetch a list of employees from a remote server:

There may be times when you need numerous promises to execute in parallel or sequence. Constructs such as Promise.all or Promise.race are especially helpful in these scenarios.

For example, imagine that you need to fetch a list of 1,000 GitHub users, and then make an additional request with the ID to fetch avatars for each of them. You don’t necessarily want to wait for each user in the sequence; you just need all the fetched avatars. We’ll examine this in more detail later when we discuss Promise.all .

Now that you have a fundamental grasp of promises, let’s look at the async/await syntax.

Understanding async/await

The async/await syntax simplifies working with promises in JavaScript. It provides an easy interface to read and write promises in a way that makes them appear synchronous.

An async/await will always return a Promise . Even if you omit the Promise keyword, the compiler will wrap the function in an immediately resolved Promise . This enables you to treat the return value of an async function as a Promise , which is useful when you need to resolve numerous asynchronous functions.

As the name implies, async always goes hand in hand with await . That is, you can only await inside an async function. The async function informs the compiler that this is an asynchronous function.

If we convert the promises from above, the syntax looks like this:

As you can immediately see, this looks more readable and appears synchronous. We told the compiler on line 3 to await the execution of angelMowersPromise before doing anything else. Then, we return the response from the myPaymentPromise .

You may have noticed that we omitted error handling. We could do this with the catch block after the .then in a promise. But what happens if we encounter an error? That leads us to try/catch .

Error handling with try/catch

We’ll refer to the employee fetching example to see the error handling in action, as it is likely to encounter an error over a network request.

Let’s say, for example, that the server is down, or perhaps we sent a malformed request. We need to pause execution to prevent our program from crashing. The syntax will look like this:

We initiated the function as an async function. We expect the return value to be either an array of employees or a string of error messages. Therefore, the type of promise is Promise<Array<Employee> | string> .

Inside the try block are the expressions we expect the function to run if there are no errors. Meanwhile, the catch block captures any errors that arise. In that case, we’d just return the message property of the error object.

The beauty of this is that any error that first occurs within the try block is thrown and caught in the catch block. An uncaught exception can lead to hard-to-debug code or even break the entire program.

Error handling using higher-order functions

While traditional try/catch blocks are effective for catching errors at the local level, they can become repetitive and clutter the main business logic when used too frequently. This is where higher-order functions come into play.

A higher-order function is a function that takes one or more functions as arguments or returns a function. In the context of error handling, a higher-order function can wrap an asynchronous function (async function) and handle any errors it might throw, thereby abstracting the try/catch logic away from the core business logic.

The main idea behind using higher-order functions for error handling in async/await is to create a wrapper function that takes an async function as an argument along with any parameters that the async function might need. Inside this wrapper, we implement a try/catch block. This approach allows us to handle errors in a centralized manner, making the code cleaner and more maintainable.

Let’s refer to the employee fetching example:

In this example, the safeFetchEmployees function uses the handleAsyncErrors higher-order function to wrap the original fetchEmployees function.

This setup automatically handles any errors that might occur during the API call, logging them and returning null to indicate an error state. The consumer of safeFetchEmployees can then check if the returned value is null to determine if the operation was successful or if an error occurred.

Concurrent execution with Promise.all

As mentioned earlier, there are times when we need promises to execute in parallel.

Let’s look at an example from our employee API. Say we first need to fetch all employees, then fetch their names, and then generate an email from the names. Obviously, we’ll need to execute the functions in a synchronous manner and also in parallel so that one doesn’t block the other.

In this case, we would make use of Promise.all . According to Mozilla , “ Promise.all is typically used after having started multiple asynchronous tasks to run concurrently and having created promises for their results so that one can wait for all the tasks being finished.”

In pseudocode, we’d have something like this:

  • Fetch all users => /employee
  • Wait for all user data. Extract the id from each user. Fetch each user => /employee/{id}
  • Generate an email for each user from their username

In the above code, fetchEmployees fetches all the employees from the baseApi . We await the response, convert it to JSON , and then return the converted data.

The most important concept to keep in mind is how we sequentially executed the code line by line inside the async function with the await keyword. We’d get an error if we tried to convert data to JSON that has not been fully awaited. The same concept applies to fetchEmployee , except that we’d only fetch a single employee. The more interesting part is the runAsyncFunctions , where we run all the async functions concurrently.

First, wrap all the methods within runAsyncFunctions inside a try/catch block. Next, await the result of fetching all the employees. We need the id of each employee to fetch their respective data, but what we ultimately need is information about the employees.

This is where we can call upon Promise.all to handle all the Promises concurrently. Each fetchEmployee Promise is executed concurrently for all the employees. The awaited data from the employees’ information is then used to generate an email for each employee with the generateEmail function.

In the case of an error, it propagates as usual, from the failed promise to Promise.all , and then becomes an exception we can catch inside the catch block.

The Awaited type

Awaited is a utility type that models operations like await in async functions. It unwraps the resolved value of a promise, discarding the promise itself, and works recursively, thereby removing any nested promise layers as well.

Awaited is the type of value that you expect to get after awaiting a promise. It helps your code understand that once you use await , you’re not dealing with a promise anymore, but with the actual data you wanted.

Here’s the basic syntax:

The awaited type does not exactly model the .then method in promises, however, Awaited can be relevant when using .then in async functions. If you use await inside a .then callback, Awaited helps infer the type of the awaited value, avoiding the need for additional type annotations.

Awaited can help clarify the type of data and awaitedValue in async functions, even when using .then for promise chaining. However, it doesn’t replace the functionality of .then itself.

Key takeaways

async and await enable us to write asynchronous code in a way that looks and behaves like synchronous code. This makes the code much easier to read, write, and understand.

Here are some some key concepts to keep in mind as you’re working on your next asynchronous project in TypeScript:

LogRocket : Full visibility into your web and mobile apps

LogRocket Dashboard Free Trial Banner

LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page and mobile apps.

Try it for free .

  • await only works inside an async function
  • The function marked with the async keyword always returns a Promise
  • If the return value inside async doesn’t return a Promise , it will be wrapped in an immediately resolved Promise
  • Execution is paused when an await keyword is encountered until a Promise is completed
  • await will either return a result from a fulfilled Promise or throw an exception from a rejected Promise

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)
  • #typescript

Hey there, want to help make our blog better?

Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

typescript multiple assignment

Stop guessing about your digital experience with LogRocket

Recent posts:.

Exploring Native File Watching In Node Js Version 22

Exploring native file watching in Node.js v22

Native file watching being stable in Node.js 22 raises a question: is it a worthy candidate to replace the industry favorite Nodemon?

typescript multiple assignment

Headless UI alternatives: Radix Primitives, React Aria, Ark UI

Check out alternatives to the Headless UI library to find unstyled components to optimize your website’s performance without compromising your design.

typescript multiple assignment

Dynamic CSS animations with the linear() easing function

Implement more dynamic CSS animations with the `linear()` easing functions, and explore the role that other easing functions play in animations.

typescript multiple assignment

Exploring the React Compiler: A detailed introduction

The new React Compiler promises to streamline frontend development with React by eliminating the need for manual memoization and optimization.

typescript multiple assignment

2 Replies to "A guide to async/await in TypeScript"

Logrocket does not catch uncaught promise rejections (at least in our case).

It can catch uncaught promise rejections—it just doesn’t catch them automatically. You can manually set it up to do so!

Leave a Reply Cancel reply

TypeScript | Union Types – Defining Multiple Types

typescript multiple assignment

TypeScript has become popular in the industry as it looks to fix or reduce a common problem found in JavaScript projects, which is the lack of type definition. Ideally, you would want to define a unique type for each variable. However, it is clear that sometimes we look to keep some of the flexibility JavaScript offers. Luckily for JavaScript developers, TypeScript offers alternatives to make your code flexible or strict when it comes to the type definition.

Table of Contents

Defining Specific Values as Types

In our previous example, the variable random can store a string , a number , a Date , or a Blob object. You can also define a specific string value as a union type. One good example is in the case you have a variable called carStyles , and you only want to get car styles as values such as Sedan, SUV, Truck, etc.

error TS2322: Type '"a"' is not assignable to type '"Sedan" | "SUV" | "Truck"'

In this case, I used only strings as types. However, you could define any kind of type such as a random number or a date.

Should I Use Union Types?

However, many developers use union types as a quick fix to enable multiple value types in variables or objects where there should be a specific value type. The poor use of union types can lead to going back to JavaScript bad practices of “save anything no matter the type” practice and create a mess on your code quickly.

More TypeScript Tips!

There is a list of TypeScript tips you might be interested in checking out

Did you like this TypeScript tip?

  • 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 operators are symbols or keywords that perform operations on one or more operands.

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.

Adds two values or expressions.
Subtracts the right operand from the left operand.
Multiplies two values or expressions
Divides the left operand by the right operand.
Returns the remainder of the division of the left operand by the right operand.
Increase the value of the operand by 1. or
Decrease the value of the operand by 1. or

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

Logical AND ( )

Returns if both operands are .

result = operand1 && operand2;

Logical OR ( )

Returns if at least one of the operands is .

result = operand1 || operand2;

Logical NOT ( )

Returns if the operand is , and vice versa.

result = !operand;

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

Equal to ( )

Returns if the values of the two operands are equal, after type coercion.

result = operand1 == operand2;

Not equal to ( )

Returns if the values of the two operands are not equal, after type coercion.

result = operand1 != operand2;

Strictly equal to ( )

Returns if the values of the two operands are equal, without type coercion (strict equality).

result = operand1 === operand2;

Strictly not equal to ( )

Returns if the values of the two operands are not equal, without type coercion (strict inequality).

result = operand1 !== operand2;

Greater than ( )

Returns if the value of the left operand is greater than the value of the right operand.

result = operand1 > operand2;

Less than ( )

Returns if the value of the left operand is less than the value of the right operand.

result = operand1 < operand2;

Greater than or equal to ( )

Returns if the value of the left operand is greater than or equal to the value of the right operand.

result = operand1 >= operand2;

Less than or equal to ( )

Returns if the value of the left operand is less than or equal to the value of the right operand

result = operand1 <= operand2;

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

Bitwise AND ( )

Performs a bitwise AND operation between each pair of corresponding bits.

result = operand1 & operand2;

Bitwise OR ( )

Performs a bitwise OR operation between each pair of corresponding bits.

result = operand1 | operand2;

Bitwise XOR ( )

Performs a bitwise XOR (exclusive OR) operation between each pair of corresponding bits.

result = operand1 ^ operand2;

Bitwise NOT ( )

Inverts the bits of the operand, changing each to and each to .

result = ~operand;

Left Shift ( )

Shifts the bits of the left operand to the left by the number of positions specified by the right operand.

result = operand1 << operand2;

Sign-propagating Right Shift ( )

Shifts the bits of the left operand to the right by the number of positions specified by the right operand, preserving the sign bit.

result = operand1 >> operand2;

Zero-fill Right Shift ( )

Shifts the bits of the left operand to the right by the number of positions specified by the right operand, filling the leftmost bits with zeros.

result = operand1 >>> operand2;

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

Syntax
Assignment ( ) Assigns the value of the right operand to the left operand.
Addition Assignment ( ) Adds the value of the right operand to the current value of the left operand and assigns the result to the left operand.
Subtraction Assignment ( ) Subtracts the value of the right operand from the current value of the left operand and assigns the result to the left operand.
Multiplication Assignment ( ) Multiplies the current value of the left operand by the value of the right operand and assigns the result to the left operand.
Division Assignment ( ) Divides the current value of the left operand by the value of the right operand and assigns the result to the left operand.
Modulus Assignment ( ) Calculates the remainder when dividing the current value of the left operand by the value of the right operand and assigns the result to the left operand.

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.

Ternary/Conditional Operator Evaluates the condition. If true, returns ; if false, returns .

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.

typeof Obtains the type of a variable, function, or property. <br> <br>
keyof Obtains the keys (property names) of a type. <br> <br>`// PersonKeys is ‘name’
Mapped Types Allows creating new types based on the properties of existing types.
Conditional Types Allows expressing a type based on a condition.

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

Name Description Syntax
String Concatenation ( ) Concatenates two strings.
Template Literals ( ) Allows embedding expressions inside strings. I am ${age} years old.`;`
String Interpolation Similar to template literals, it allows inserting variables into strings.
String Methods Various methods for manipulating strings.
String Length Property ( ) Returns the length of a string.

Please Login to comment...

Similar reads.

  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

How to assign a multiline string literal to a variable?

How do I convert this Ruby code with a multiline string into JavaScript?

Heretic Monkey's user avatar

43 Answers 43

ECMAScript 6 (ES6) introduces a new type of literal, namely template literals . They have many features, variable interpolation among others, but most importantly for this question, they can be multiline.

A template literal is delimited by backticks :

(Note: I'm not advocating to use HTML in strings)

Browser support is OK , but you can use transpilers to be more compatible.

Original ES5 answer:

Javascript doesn't have a here-document syntax. You can escape the literal newline, however, which comes close:

sodimel's user avatar

  • 283 Be warned: some browsers will insert newlines at the continuance, some will not. –  staticsan Commented Apr 30, 2009 at 2:22
  • 45 Visual Studio 2010 seems to be confused by this syntax as well. –  jcollum Commented Apr 17, 2011 at 21:58
  • 63 @Nate It is specified in ECMA-262 5th Edition section 7.8.4 and called LineContinuation : "A line terminator character cannot appear in a string literal, except as part of a LineContinuation to produce the empty character sequence. The correct way to cause a line terminator character to be part of the String value of a string literal is to use an escape sequence such as \n or \u000A." –  some Commented Sep 25, 2012 at 2:28
  • 24 I don't see why you'd do this when browsers treat it inconsistently. "line1\n" + "line2" across multiple lines is readable enough and you're guaranteed consistent behavior. –  SamStephens Commented Mar 20, 2013 at 20:14
  • 24 "Browser support is OK"... not supported by IE11 - not OK –  Tom Andraszek Commented May 25, 2017 at 5:18

ES6 Update:

As the first answer mentions, with ES6/Babel, you can now create multi-line strings simply by using backticks:

Interpolating variables is a popular new feature that comes with back-tick delimited strings:

This just transpiles down to concatenation:

Google's JavaScript style guide recommends to use string concatenation instead of escaping newlines: Do not do this: var myString = 'A rather long string of English text, an error message \ actually that just keeps going and going -- an error \ message to make the Energizer bunny blush (right through \ those Schwarzenegger shades)! Where was I? Oh yes, \ you\'ve got an error and all the extraneous whitespace is \ just gravy. Have a nice day.'; The whitespace at the beginning of each line can't be safely stripped at compile time; whitespace after the slash will result in tricky errors; and while most script engines support this, it is not part of ECMAScript. Use string concatenation instead: var myString = 'A rather long string of English text, an error message ' + 'actually that just keeps going and going -- an error ' + 'message to make the Energizer bunny blush (right through ' + 'those Schwarzenegger shades)! Where was I? Oh yes, ' + 'you\'ve got an error and all the extraneous whitespace is ' + 'just gravy. Have a nice day.';

Devin Rhode's user avatar

  • 29 I don't understand Google's recommendation. All browsers except extremely old ones support the backslash followed by newline approach, and will continue to do so in the future for backward compatibility. The only time you'd need to avoid it is if you needed to be sure that one and only one newline (or no newline) was added at the end of each line (see also my comment on the accepted answer). –  Matt Browne Commented Feb 26, 2013 at 18:40
  • 8 Note that template strings aren't supported in IE11, Firefox 31, Chrome 35, or Safari 7. See kangax.github.io/compat-table/es6 –  EricP Commented May 24, 2014 at 2:41
  • 46 @MattBrowne Google's recommendation is already documented by them, in order of importance of reasons: (1) The whitespace at the beginning of each line [in the example, you don't want that whitespace in your string but it looks nicer in the code] (2) whitespace after the slash will result in tricky errors [if you end a line with \ instead of `\` it's hard to notice] and (3) while most script engines support this, it is not part of ECMAScript [i.e. why use nonstandard features?] Remember it's a style guide, which is about making code easy to read+maintain+debug: not just "it works" correct. –  ShreevatsaR Commented Jul 31, 2016 at 20:29
  • 3 amazing that after all these years string concatenation is still the best/safest/most compliant way to go with this. template literals (above answer) don't work in IE and escaping lines is just a mess that you're soon going to regret –  Tiago Duarte Commented Nov 11, 2016 at 12:31
  • 3 Found out the hard way that older versions of Android do not support the backticks so if you have an Android app using the webView your backticks cause your app to not run! –  Michael Fever Commented Jun 26, 2019 at 19:45

the pattern text = <<"HERE" This Is A Multiline String HERE is not available in js (I remember using it much in my good old Perl days).

To keep oversight with complex or long multiline strings I sometimes use an array pattern:

or the pattern anonymous already showed (escape newline), which can be an ugly block in your code:

Here's another weird but working 'trick' 1 :

external edit: jsfiddle

ES20xx supports spanning strings over multiple lines using template strings :

1 Note: this will be lost after minifying/obfuscating your code

KooiInc's user avatar

  • 40 Please don't use the array pattern. It will be slower than plain-old string concatenation in most cases. –  BMiner Commented Jul 17, 2011 at 12:39
  • 86 The array pattern is more readable and the performance loss for an application is often negligible. As that perf test shows, even IE7 can do tens of thousands of operations per second. –  Benjamin Atkin Commented Aug 20, 2011 at 8:16
  • 23 +1 for an elegant alternative that not only works the same way in all browsers, but is also future-proof. –  Pavel Commented May 21, 2012 at 6:06
  • 28 @KooiInc Your tests start with the array already created, that skews the results. If you add the initialization of the array, straight concatenation is faster jsperf.com/string-concat-without-sringbuilder/7 See stackoverflow.com/questions/51185/… As a trick for newlines, it may be OK, but it's definitely doing more work than it should –  Ruan Mendes Commented Aug 4, 2013 at 8:02
  • 12 @BMiner: 1) "Premature optimization is the root of all evil" - Donald Knuth, and 2) 'readability' is in the eye of the beholder –  user2418182 Commented Mar 25, 2014 at 15:27

You can have multiline strings in pure JavaScript.

This method is based on the serialization of functions, which is defined to be implementation-dependent . It does work in the most browsers (see below), but there's no guarantee that it will still work in the future, so do not rely on it.

Using the following function:

You can have here-documents like this:

The method has successfully been tested in the following browsers (not mentioned = not tested):

  • Opera 9.50 - 12 (not in 9-)
  • Safari 4 - 6 (not in 3-)
  • Chrome 1 - 45
  • Firefox 17 - 21 ( not in 16- )
  • Rekonq 0.7.0 - 0.8.0
  • Not supported in Konqueror 4.7.4

Be careful with your minifier, though. It tends to remove comments. For the YUI compressor , a comment starting with /*! (like the one I used) will be preserved.

I think a real solution would be to use CoffeeScript .

ES6 UPDATE: You could use backtick instead of creating a function with a comment and running toString on the comment. The regex would need to be updated to only strip spaces. You could also have a string prototype method for doing this:

Someone should write this .removeIndentation string method... ;)

gpl's user avatar

  • 287 What!? creating and decompiling a Function to hack a multiline comment into being a multiline string? Now that's ugly. –  fforw Commented Jun 17, 2011 at 15:49
  • 5 jsfiddle.net/fqpwf works in Chrome 13 and IE8/9, but not FF6. I hate to say it, but I like it, and if it could be an intentional feature of each browser (so that it wouldn't disappear), I'd use it. –  Jason Kleban Commented Sep 9, 2011 at 21:36
  • 3 @uosɐſ: for it to be intentional, it'd have to be in the spec; or so widespread used, that browser makers wouldn't want to remove this "accidental" feature. Thanks for the experiments though... Try some coffeescript. –  Jordão Commented Sep 10, 2011 at 2:37
  • 2 a.toString().substring(15, a.toString().length-4) also works, and doesn't need to scan the entire string (although it most likely will and the counting makes it another scan anyway. Oh wel.) –  Lodewijk Commented Jan 8, 2012 at 23:53
  • 3 Extremely handy. I'm using it for (Jasmine) unit tests, but avoiding it for production code. –  Jason Commented Jul 13, 2012 at 5:23

You can do this...

  • First example is great and simple. Much better than the \ approach as I'm not sure how browser's would handle the backslash as an escape character and as a multi-line character. –  Matt K Commented Nov 3, 2011 at 19:13
  • The CDATA code (E4X) is obsolete and will soon stop working even in Firefox . –  Brock Adams Commented Nov 22, 2012 at 12:16
  • e4x.js would be the good future-proof solution –  Paul Sweatte Commented Jan 19, 2013 at 2:54

I came up with this very jimmy rigged method of a multi lined string. Since converting a function into a string also returns any comments inside the function you can use the comments as your string using a multilined comment /**/. You just have to trim off the ends and you have your string.

Luke's user avatar

  • 50 This is absolutely terrifying. I love it (although you may need to do a regex match because I'm not sure how precise the whitespace for toString() is. –  Kevin Cox Commented Apr 7, 2013 at 21:53
  • 2 This solution does not seem to work in firefox, maybe it's a security feature for the browser? EDIT: Nevermind, it only does not work for Firefox Version 16. –  Bill Software Engineer Commented Jun 6, 2013 at 19:18
  • 59 Also beware of minifiers that strip comments... :D –  jondavidjohn Commented Oct 22, 2013 at 19:07
  • 9 This is why we can't have nice things. –  Danilo M. Oliveira Commented Oct 15, 2018 at 18:39
  • 8 You can do some weird stuff in javascript land. Though in all honesty, you should never use this. –  Luke Commented Oct 25, 2018 at 23:25

I'm surprised I didn't see this, because it works everywhere I've tested it and is very useful for e.g. templates:

Does anybody know of an environment where there is HTML but it doesn't work?

Peter V. Mørch's user avatar

  • 25 Anywhere you don't want to put your strings into seperate and distant script elements. –  Lodewijk Commented Jan 9, 2012 at 1:12
  • 10 A valid objection! It isn't perfect. But for templates, that separation is not only ok, but perhaps even encouraged. –  Peter V. Mørch Commented Feb 3, 2012 at 9:03
  • 2 I prefer splitting everything over 80/120 characters into multiline, I'm afraid that's more than just templates. I now prefer 'line1 ' + 'line2' syntax. It's also the fastest (although this might rival it for really large texts). It's a nice trick though. –  Lodewijk Commented Feb 3, 2012 at 22:51
  • 29 actually, this is HTML not Javascript :-/ –  CpILL Commented May 22, 2012 at 8:54
  • 6 however, the task of obtaining a multiline string in javascript can be done this way –  Davi Fiamenghi Commented Jul 30, 2013 at 21:41

I solved this by outputting a div, making it hidden, and calling the div id by jQuery when I needed it.

Then when I need to get the string, I just use the following jQuery:

Which returns my text on multiple lines. If I call

enter image description here

  • 4 Thanks for this! It's the only answer I've found that solves my problem, which involves unknown strings that may contain any combination of single and double quotes being directly inserted into the code with no opportunity for pre-encoding. (it's coming from a templating language that creates the JS -- still from a trusted source and not a form submission, so it's not TOTALLY demented). –  octern Commented Jun 23, 2013 at 17:19
  • This was the only method that actually worked for me to create a multi-line javascript string variable from a Java String. –  beginner_ Commented Aug 6, 2013 at 12:06
  • 4 What if the string is HTML? –  Dan Dascalescu Commented Jan 24, 2014 at 8:39
  • 4 $('#UniqueID').content() –  mplungjan Commented Jan 24, 2014 at 9:28
  • 1 @Pacerier Everything I've read, from Google as well as other sites, says that nowadays Google does index display:none content, most likely due to the popularity of JavaScript-styled front-ends. (For example, an FAQ page with hide/show functionality.) You need to be careful though, because Google says they can punish you if the hidden content appears to be designed to artificially inflate your SEO rankings. –  Gavin Commented Aug 8, 2017 at 13:12

There are multiple ways to achieve this

1. Slash concatenation

2. regular concatenation

3. Array Join concatenation

Performance wise, Slash concatenation (first one) is the fastest.

Refer this test case for more details regarding the performance

With the ES2015 , we can take advantage of its Template strings feature. With it, we just need to use back-ticks for creating multi line strings

Vignesh Subramanian's user avatar

  • 11 I think it's that you've just regurgitated what has already on the page for five years, but in a cleaner way. –  RandomInsano Commented Aug 2, 2014 at 18:22
  • won't slash concatenation also include the whitespace in beginning of lines? –  f.khantsis Commented May 9, 2017 at 23:39

Using script tags:

  • add a <script>...</script> block containing your multiline text into head tag;

get your multiline text as is... (watch out for text encoding: UTF-8, ASCII)

jpfreire's user avatar

  • I think this strategy is clean & far underused. jsrender uses this. –  xdhmoore Commented Jan 9, 2015 at 15:57
  • I'm using this with innerText iso innerHTML, But how do I make sure that the whitespaces are preserved ? –  David Nouls Commented Jul 16, 2015 at 8:53
  • Also ajax queries in case you are using them. You can try to change your headers xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); I don't remember having other problems than mistyping comments in JS. Spaces where no problems. –  jpfreire Commented Oct 28, 2015 at 5:40

A simple way to print multiline strings in JavaScript is by using template literals(template strings) denoted by backticks (` `). you can also use variables inside a template string-like (` name is ${value} `)

You can also

const value = `multiline` const text = `This is a ${value} string in js`; console.log(text);

itsankitbhusal's user avatar

I like this syntax and indendation:

(but actually can't be considered as multiline string)

semente's user avatar

  • 3 I use this, except I put the '+' at the end of the preceding line, to make it clear the statement is continued on the next line. Your way does line up the indents more evenly though. –  Sean Commented Oct 4, 2012 at 8:54
  • @Sean i use this too, and i still prefer put the '+' at the beginning of each new line added, and the final ';' on a new line, cuz i found it more 'correct'. –  AgelessEssence Commented Nov 14, 2013 at 5:06
  • 7 putting the + at the beginning allows one to comment out that line without having to edit other lines when its the first/last line of the sequence. –  moliad Commented Dec 12, 2013 at 15:38
  • 3 I prefer the + at the front too as visually I do not need to scan to the end of the line to know the next one is a continuation. –  Daniel Sokolowski Commented May 7, 2014 at 15:40

Downvoters : This code is supplied for information only.

This has been tested in Fx 19 and Chrome 24 on Mac

var new_comment; /*<<<EOF <li class="photobooth-comment"> <span class="username"> <a href="#">You</a>: </span> <span class="comment-text"> $text </span> @<span class="comment-time"> 2d </span> ago </li> EOF*/ // note the script tag here is hardcoded as the FIRST tag new_comment=document.currentScript.innerHTML.split("EOF")[1]; document.querySelector("ul").innerHTML=new_comment.replace('$text','This is a dynamically created text'); <ul></ul>

mplungjan's user avatar

  • 17 That's horrific. +1. And you can use document.currentScript instead of getElement... –  Orwellophile Commented May 27, 2015 at 10:00
  • 1 Undefined "you" in chrome for osx –  mplungjan Commented May 27, 2015 at 16:46
  • 1 jsfiddle-fixed - I must have had "you" defined globally in my console. Works now (chrome/osx). The nice thing about adding the comment to a var is that you're not in a function context, jsfiddle-function-heredoc although the function thing would be cool for class methods. might be better to pass it a replace { this: that } object anyways. fun to push something crazy to the limit anyway :) –  Orwellophile Commented Jun 1, 2015 at 16:44
  • 1 Forget the haters. This is the only correct answer bar ES6. All the other answers require concatenation, computation of some sort, or escaping. This is actually pretty cool and I'm going to use it as a way to add documentation to a game I'm working on as a hobby. As long as this trick isn't used for anything that could invoke a bug (I can see how someone would go "Semicolon, derp. Lets put the comment on the next line." and then it breaks your code.) But, is that really a big deal in my hobby game? No, and I can use the cool trick for something useful. Great answer. –  Thomas Dignan Commented Jul 27, 2015 at 21:10
  • 2 I've never been brave enough to use this technique in production code, but where I DO use it a lot is in unit testing, where often it's easiest to dump the value of some structure as a (quite long) string and compare it to what it 'should' be. –  Ben McIntyre Commented Feb 3, 2016 at 0:00

There's this library that makes it beautiful:

https://github.com/sindresorhus/multiline

Shahar 'Dawn' Or's user avatar

  • 1 This support in nodejs , using in browser must becareful. –  Huei Tan Commented May 5, 2014 at 8:52
  • 3 @HueiTan Docs state it also works in the browser. Which makes sense - it's just Function.prototype.String() . –  mikemaccana Commented Jul 13, 2014 at 19:14
  • ya but it said "While it does work fine in the browser, it's mainly intended for use in Node.js. Use at your own risk.While it does work fine in the browser, it's mainly intended for use in Node.js. Use at your own risk." (Just becareful XD) –  Huei Tan Commented Jul 14, 2014 at 9:37
  • @HueiTanYep I read that part. But Function.prototype.toString() is pretty stable and well known. –  mikemaccana Commented Jul 14, 2014 at 10:52
  • 1 Best answer for me because it at least achieves multiline without all the rubbish in the middle(The rubbish at the beginning and ends I can deal with). –  Damien Golding Commented Aug 27, 2014 at 6:25

Found a lot of over engineered answers here. The two best answers in my opinion were:

which eventually logs:

That logs it correctly but it's ugly in the script file if str is nested inside functions / objects etc...:

My really simple answer with regex which logs the str correctly:

Please note that it is not the perfect solution but it works if you are sure that after the new line (\n) at least one space will come (+ means at least one occurrence). It also will work with * (zero or more).

You can be more explicit and use {n,} which means at least n occurrences.

Niv's user avatar

  • 7 Why wouldn't you just [ "line", "line2", "line3" ].join("\n") . –  Kaz Commented Jan 21, 2022 at 19:18

The equivalent in javascript is:

Here's the specification . See browser support at the bottom of this page . Here are some examples too.

Lonnie Best's user avatar

Ruby produce : "This\nIs\nA\nMultiline\nString\n" - below JS produce exact same string

text = `This Is A Multiline String ` // TEST console.log(JSON.stringify(text)); console.log(text);

This is improvement to Lonnie Best answer because new-line characters in his answer are not exactly the same positions as in ruby output

Kamil Kiełczewski's user avatar

  • text is string why json.stringify? –  FlatLander Commented Jul 12, 2020 at 11:20
  • 1 @FlatLander this is only for test - to see where are exactly new-line characters \n (to compare with ruby output (working example linked in answer) ) - this is improvement of Lonnie answer because new-line characters in his answer are not exactly the same positions as in ruby output –  Kamil Kiełczewski Commented Jul 12, 2020 at 20:51

This works in IE, Safari, Chrome and Firefox:

stillatmycomputer's user avatar

  • 8 Just think about it. Do you think it's valid? Don't you think it can cause display problems? –  Sk8erPeter Commented Feb 24, 2012 at 1:55
  • 6 Why the downvotes? This is a creative answer, if not very practical! –  dotancohen Commented Feb 29, 2012 at 2:32
  • 3 no, it's not. One should rather use templates: $.tmpl() ( api.jquery.com/tmpl ), or EJS ( embeddedjs.com/getting_started.html ), etc. One reason for downvotes is that it's really far from a valid code and using this can cause huge display problems. –  Sk8erPeter Commented Mar 24, 2012 at 0:07
  • I hope no one ever uses this answer in practice, but it's a neat idea –  DCShannon Commented Mar 13, 2015 at 23:48
  • Edge case when you have ' within the html. in that case you may have to use html entities &#39; . –  borracciaBlu Commented Dec 18, 2020 at 4:25

to sum up, I have tried 2 approaches listed here in user javascript programming (Opera 11.01):

  • this one didn't work: Creating multiline strings in JavaScript
  • this worked fairly well, I have also figured out how to make it look good in Notepad++ source view: Creating multiline strings in JavaScript

So I recommend the working approach for Opera user JS users. Unlike what the author was saying:

It doesn't work on firefox or opera; only on IE, chrome and safari.

It DOES work in Opera 11. At least in user JS scripts. Too bad I can't comment on individual answers or upvote the answer, I'd do it immediately. If possible, someone with higher privileges please do it for me.

Community's user avatar

  • This is my first actual comment. I have gained the upvote privilege 2 days ago so so I immediately upvoted the one answer I mentioned above. Thank you to anyone who did upvote my feeble attempt to help. –  Tyler Commented Jul 24, 2011 at 12:34
  • Thanks to everyone who actually upvoted this answer: I have now enough privileges to post normal comments! So thanks again. –  Tyler Commented Aug 31, 2012 at 2:41

My extension to https://stackoverflow.com/a/15558082/80404 . It expects comment in a form /*! any multiline comment */ where symbol ! is used to prevent removing by minification (at least for YUI compressor)

pocheptsov's user avatar

Updated for 2015 : it's six years later now: most people use a module loader, and the main module systems each have ways of loading templates. It's not inline, but the most common type of multiline string are templates, and templates should generally be kept out of JS anyway .

require.js: 'require text'.

Using require.js 'text' plugin , with a multiline template in template.html

NPM/browserify: the 'brfs' module

Browserify uses a 'brfs' module to load text files. This will actually build your template into your bundled HTML.

mikemaccana's user avatar

If you're willing to use the escaped newlines, they can be used nicely . It looks like a document with a page border .

enter image description here

  • 3 Wouldn't this add extraneous blank spaces? –  tomByrer Commented Dec 6, 2015 at 12:29
  • 1 @tomByrer Yes, good observation. It's only good for strings which you don't care about white space, e.g. HTML. –  seo Commented Dec 6, 2015 at 23:02

Easiest way to make multiline strings in Javascrips is with the use of backticks ( `` ). This allows you to create multiline strings in which you can insert variables with ${variableName} .

let name = 'Willem'; let age = 26; let multilineString = ` my name is: ${name} my age is: ${age} `; console.log(multilineString);

compatibility :

  • It was introduces in ES6 // es2015
  • It is now natively supported by all major browser vendors (except internet explorer)

Check exact compatibility in Mozilla docs here

Willem van der Veen's user avatar

  • Is this now compatible with all recent browsers? Or are there some browsers which still do not support this syntax? –  cmpreshn Commented Sep 28, 2018 at 3:37
  • Sorry for my extreme late comment, edited the answer added compatibility info ;) –  Willem van der Veen Commented Oct 1, 2018 at 21:28

The ES6 way of doing it would be by using template literals:

More reference here

jenil christo's user avatar

  • This answer is not only small, incomplete and bad formatted, but also doesn't add absolutely anything to the previous answers. Flagging it and hopping to be deleted. –  Victor Schröder Commented Jan 18, 2019 at 17:43

You can use TypeScript (JavaScript SuperSet), it supports multiline strings, and transpiles back down to pure JavaScript without overhead:

If you'd want to accomplish the same with plain JavaScript:

Note that the iPad/Safari does not support 'functionName.toString()'

If you have a lot of legacy code, you can also use the plain JavaScript variant in TypeScript (for cleanup purposes):

and you can use the multiline-string object from the plain JavaScript variant, where you put the templates into another file (which you can merge in the bundle).

You can try TypeScript at http://www.typescriptlang.org/Playground

Stefan Steiger's user avatar

  • Any documentation on the iPad/Safari limitation? MDN seems to think it's all good - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… –  Campbeln Commented Aug 5, 2017 at 18:15
  • @Campbeln: CoWorker told me this (he used the code). Haven't tested it myselfs. Might also depend on the iPad/Safari version - so probably depends. –  Stefan Steiger Commented Aug 6, 2017 at 16:07

ES6 allows you to use a backtick to specify a string on multiple lines. It's called a Template Literal. Like this:

Using the backtick works in NodeJS, and it's supported by Chrome, Firefox, Edge, Safari, and Opera.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

earl3s's user avatar

You can use tagged templates to make sure you get the desired output.

For example:

Pedro Andrade's user avatar

Also do note that, when extending string over multiple lines using forward backslash at end of each line, any extra characters (mostly spaces, tabs and comments added by mistake) after forward backslash will cause unexpected character error, which i took an hour to find out

Prakash GPz's user avatar

Please for the love of the internet use string concatenation and opt not to use ES6 solutions for this. ES6 is NOT supported all across the board, much like CSS3 and certain browsers being slow to adapt to the CSS3 movement. Use plain ol' JavaScript, your end users will thank you.

var str = "This world is neither flat nor round. "+ "Once was lost will be found";

Pragmatiq's user avatar

  • 3 while i agree with your point, i wouldn't call javascript "good" ol –  user151496 Commented Mar 5, 2018 at 0:18
  • 1 How does this admonition stand up in 2022? –  Ken Ingram Commented Mar 15, 2022 at 5:12
  • It is the responsibility of the end user to keep their browser updated. It is the responsibility of the developer to code in the right way and make the product better. –  user3221512 Commented Dec 7, 2022 at 11:10

Multiline string with variables

Abhishek Goel's user avatar

Not the answer you're looking for? Browse other questions tagged javascript string multiline heredoc or ask your own question .

  • Featured on Meta
  • We spent a sprint addressing your requests — here’s how it went
  • Upcoming initiatives on Stack Overflow and across the Stack Exchange network...
  • What makes a homepage useful for logged-in users

Hot Network Questions

  • Does the cosmological constant entail a mass for the graviton?
  • These two Qatar flights with slightly different times and different flight number must actually be the same flight, right?
  • Mathematical Induction over two numbers
  • Is it an option for the ls utility specified in POSIX.1-2017?
  • How can one count how many pixels a GIF image has via command line?
  • Coincidence between coefficients of tanh(tan(x/2)) and Chow ring computations?
  • What enforcement exists for medical informed consent?
  • How to turn a sum into an integral?
  • Does the damage from Thunderwave occur before or after the target is moved
  • Canon PowerShot A80 keeps shutting down and asking to change the battery pack. What should I do?
  • Is it alright to display mean CPU usage of algorithm instead of CPU cores available?
  • 8x8 grid with no unmarked L-pentomino
  • How is 11:22 four minutes slow if it's actually 11:29?
  • How can I get the value of the f(1/2) is 11/4 not 2.75 when I use \pgfmathprintnumber\pgfmathresult?
  • Quantum: why linear combination of vectors (superposition) is described as "both at the same time"?
  • Submitting 2 manuscripts explaining the same scientific fact but by two different methods
  • Is infinity a number?
  • How should I deal with curves in new deck boards during installation?
  • Generate filesystem usage report using Awk
  • Is it possible to have multiple versions of MacOS on the same laptop at the same time?
  • Intelligence vs Wisdom in D&D
  • Identify the story about an author whose work-in-progress is completed by a computer
  • Citation hunting: Floer on spectral sequences
  • Why does King Aegon speak to his dragon in the Common Tongue (English)?

typescript multiple assignment

Was this page helpful?

Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript.

Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.

Numeric enums

We’ll first start off with numeric enums, which are probably more familiar if you’re coming from other languages. An enum can be defined using the enum keyword.

Above, we have a numeric enum where Up is initialized with 1 . All of the following members are auto-incremented from that point on. In other words, Direction.Up has the value 1 , Down has 2 , Left has 3 , and Right has 4 .

If we wanted, we could leave off the initializers entirely:

Here, Up would have the value 0 , Down would have 1 , etc. This auto-incrementing behavior is useful for cases where we might not care about the member values themselves, but do care that each value is distinct from other values in the same enum.

Using an enum is simple: just access any member as a property off of the enum itself, and declare types using the name of the enum:

Numeric enums can be mixed in computed and constant members (see below) . The short story is, enums without initializers either need to be first, or have to come after numeric enums initialized with numeric constants or other constant enum members. In other words, the following isn’t allowed:

String enums

String enums are a similar concept, but have some subtle runtime differences as documented below. In a string enum, each member has to be constant-initialized with a string literal, or with another string enum member.

While string enums don’t have auto-incrementing behavior, string enums have the benefit that they “serialize” well. In other words, if you were debugging and had to read the runtime value of a numeric enum, the value is often opaque - it doesn’t convey any useful meaning on its own (though reverse mapping can often help). String enums allow you to give a meaningful and readable value when your code runs, independent of the name of the enum member itself.

Heterogeneous enums

Technically enums can be mixed with string and numeric members, but it’s not clear why you would ever want to do so:

Unless you’re really trying to take advantage of JavaScript’s runtime behavior in a clever way, it’s advised that you don’t do this.

Computed and constant members

Each enum member has a value associated with it which can be either constant or computed . An enum member is considered constant if:

It is the first member in the enum and it has no initializer, in which case it’s assigned the value 0 :

It does not have an initializer and the preceding enum member was a numeric constant. In this case the value of the current enum member will be the value of the preceding enum member plus one.

The enum member is initialized with a constant enum expression. A constant enum expression is a subset of TypeScript expressions that can be fully evaluated at compile time. An expression is a constant enum expression if it is:

  • a literal enum expression (basically a string literal or a numeric literal)
  • a reference to previously defined constant enum member (which can originate from a different enum)
  • a parenthesized constant enum expression
  • one of the + , - , ~ unary operators applied to constant enum expression
  • + , - , * , / , % , << , >> , >>> , & , | , ^ binary operators with constant enum expressions as operands

It is a compile time error for constant enum expressions to be evaluated to NaN or Infinity .

In all other cases enum member is considered computed.

Union enums and enum member types

There is a special subset of constant enum members that aren’t calculated: literal enum members. A literal enum member is a constant enum member with no initialized value, or with values that are initialized to

  • any string literal (e.g. "foo" , "bar" , "baz" )
  • any numeric literal (e.g. 1 , 100 )
  • a unary minus applied to any numeric literal (e.g. -1 , -100 )

When all members in an enum have literal enum values, some special semantics come into play.

The first is that enum members also become types as well! For example, we can say that certain members can only have the value of an enum member:

The other change is that enum types themselves effectively become a union of each enum member. With union enums, the type system is able to leverage the fact that it knows the exact set of values that exist in the enum itself. Because of that, TypeScript can catch bugs where we might be comparing values incorrectly. For example:

In that example, we first checked whether x was not E.Foo . If that check succeeds, then our || will short-circuit, and the body of the ‘if’ will run. However, if the check didn’t succeed, then x can only be E.Foo , so it doesn’t make sense to see whether it’s not equal to E.Bar .

Enums at runtime

Enums are real objects that exist at runtime. For example, the following enum

can actually be passed around to functions

Enums at compile time

Even though Enums are real objects that exist at runtime, the keyof keyword works differently than you might expect for typical objects. Instead, use keyof typeof to get a Type that represents all Enum keys as strings.

Reverse mappings

In addition to creating an object with property names for members, numeric enums members also get a reverse mapping from enum values to enum names. For example, in this example:

TypeScript compiles this down to the following JavaScript:

In this generated code, an enum is compiled into an object that stores both forward ( name -> value ) and reverse ( value -> name ) mappings. References to other enum members are always emitted as property accesses and never inlined.

Keep in mind that string enum members do not get a reverse mapping generated at all.

const enums

In most cases, enums are a perfectly valid solution. However sometimes requirements are tighter. To avoid paying the cost of extra generated code and additional indirection when accessing enum values, it’s possible to use const enums. Const enums are defined using the const modifier on our enums:

Const enums can only use constant enum expressions and unlike regular enums they are completely removed during compilation. Const enum members are inlined at use sites. This is possible since const enums cannot have computed members.

in generated code will become

Const enum pitfalls

Inlining enum values is straightforward at first, but comes with subtle implications. These pitfalls pertain to ambient const enums only (basically const enums in .d.ts files) and sharing them between projects, but if you are publishing or consuming .d.ts files, these pitfalls likely apply to you, because tsc --declaration transforms .ts files into .d.ts files.

  • For the reasons laid out in the isolatedModules documentation , that mode is fundamentally incompatible with ambient const enums. This means if you publish ambient const enums, downstream consumers will not be able to use isolatedModules and those enum values at the same time.
  • You can easily inline values from version A of a dependency at compile time, and import version B at runtime. Version A and B’s enums can have different values, if you are not very careful, resulting in surprising bugs , like taking the wrong branches of if statements. These bugs are especially pernicious because it is common to run automated tests at roughly the same time as projects are built, with the same dependency versions, which misses these bugs completely.
  • importsNotUsedAsValues: "preserve" will not elide imports for const enums used as values, but ambient const enums do not guarantee that runtime .js files exist. The unresolvable imports cause errors at runtime. The usual way to unambiguously elide imports, type-only imports , does not allow const enum values , currently.

Here are two approaches to avoiding these pitfalls:

Do not use const enums at all. You can easily ban const enums with the help of a linter. Obviously this avoids any issues with const enums, but prevents your project from inlining its own enums. Unlike inlining enums from other projects, inlining a project’s own enums is not problematic and has performance implications.

Do not publish ambient const enums, by deconstifying them with the help of preserveConstEnums . This is the approach taken internally by the TypeScript project itself . preserveConstEnums emits the same JavaScript for const enums as plain enums. You can then safely strip the const modifier from .d.ts files in a build step .

This way downstream consumers will not inline enums from your project, avoiding the pitfalls above, but a project can still inline its own enums, unlike banning const enums entirely.

Ambient enums

Ambient enums are used to describe the shape of already existing enum types.

One important difference between ambient and non-ambient enums is that, in regular enums, members that don’t have an initializer will be considered constant if its preceding enum member is considered constant. By contrast, an ambient (and non-const) enum member that does not have an initializer is always considered computed.

Objects vs Enums

In modern TypeScript, you may not need an enum when an object with as const could suffice:

The biggest argument in favour of this format over TypeScript’s enum is that it keeps your codebase aligned with the state of JavaScript, and when/if enums are added to JavaScript then you can move to the additional syntax.

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  (17)

Last updated: Jul 08, 2024  

COMMENTS

  1. Declaring multiple TypeScript variables with the same type

    This does not explicitly define signatureTypeName as a string; it is implicitly a string because that is the type of the first value assigned to it. You could initially assign anything to signatureTypeName and it would compile. For example, you could have done let a: string = "", b = 4, which defeats OP's question, where he/she stated they want both variables to be the same type.

  2. TypeScript: Documentation

    var declarations. Declaring a variable in JavaScript has always traditionally been done with the var keyword. var a = 10; As you might've figured out, we just declared a variable named a with the value 10. We can also declare a variable inside of a function: function f() {.

  3. Destructuring

    The method of structuring in JavaScript is the object literal: var foo = { bar: { bas: 123 } }; Without the awesome structuring support built into JavaScript, creating new objects on the fly would indeed be very cumbersome. Destructuring brings the same level of convenience to getting data out of a structure.

  4. How to dynamically assign properties to an object in TypeScript

    Solution 1: Explicitly type the object at declaration time. This is the easiest solution to reason through. At the time you declare the object, go ahead and type it, and assign all the relevant values: type Org = {. name: string. } const organization: Org = {. name: "Logrocket" } See this in the TypeScript Playground.

  5. 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.

  6. Return Multiple values from a Function in TypeScript

    To return multiple values from a function in TypeScript, group the values in an array and return the array, e.g. `return [myValue1, myValue2] as const`. ... Note that the order of assignment and the order of the values in the array is the same. If you don't want to use destructuring, you can explicitly access the values by using bracket ...

  7. TypeScript: Documentation

    Conditional Types. At the heart of most useful programs, we have to make decisions based on input. JavaScript programs are no different, but given the fact that values can be easily introspected, those decisions are also based on the types of the inputs. Conditional types help describe the relation between the types of inputs and outputs.

  8. Assigning Types to Variables

    Assigning Types to Variables. Here we have an interface that represents a user within our system: id: number; firstName: string; lastName: string; isAdmin: boolean; There's a function called getUserId that takes in a user, and returns its id. Our test is currently failing, becaus.

  9. Type assignment in typescript

    TypeScript infers the type of "age" as "number" based on its initial value of 25. This allows us to write more concise code without sacrificing type safety. Union Types. Another powerful feature of TypeScript is the ability to assign multiple types to a variable using union types. Union types are denoted by the pipe (|) symbol.

  10. Nullish Coalescing: The ?? Operator in TypeScript

    Nullish Coalescing: The ?? Operator in TypeScript August 6, 2020. TypeScript 3.7 added support for the ?? operator, which is known as the nullish coalescing operator.We can use this operator to provide a fallback value for a value that might be null or undefined. #Truthy and Falsy Values in JavaScript Before we dive into the ?? operator, let's recall that JavaScript values can either be truthy ...

  11. How To Add Multiple Constructors In TypeScript?

    Although TypeScript doesn't support multiple constructors, you can still achieve similar behavior. In TypeScript, you can achieve a similar behavior to adding multiple constructors by: Adding constructor overloads AND implementing a custom type guard. Using the static factory method to construct a class. Adding a partial class argument to the ...

  12. TypeScript: Documentation

    TypeScript has two special types, null and undefined, that have the values null and undefined respectively. We mentioned these briefly in the Basic Types section. By default, the type checker considers null and undefined assignable to anything. Effectively, null and undefined are valid values of every type.

  13. A guide to async/await in TypeScript

    Awaited is a utility type that models operations like await in async functions. It unwraps the resolved value of a promise, discarding the promise itself, and works recursively, thereby removing any nested promise layers as well. Awaited is the type of value that you expect to get after awaiting a promise.

  14. How to properly handle TypeScript values with multiple types

    Typescript (2.7+) > Multiple types for a parameter > Handle specific properties. 3. Passing types as values in typescript. 1. Handling different type of data. 0. Typescript How To handle Type or Array of Types. 2. How to access an object that could have several data types in an Angular template. 0.

  15. TypeScript

    As previously mentioned, TypeScript includes union types as a way to give you the flexibility you need to handle different logical scenarios. For example, if you are storing CSS property values such as opacity or margin, you will see you could get values as a string or as a number. In the case of margin you could get different values such as ...

  16. TypeScript: Documentation

    Note that in this example, TypeScript could infer both the type of the Input type parameter (from the given string array), as well as the Output type parameter based on the return value of the function expression (number).. Constraints. We've written some generic functions that can work on any kind of value. Sometimes we want to relate two values, but can only operate on a certain subset of ...

  17. TypeScript Operators

    TypeScript operators are symbols or keywords that perform operations on one or more operands. Below are the different TypeScript Operators: Table of Content. TypeScript Arithmetic operators. TypeScript Logical operators. TypeScript Relational operators. TypeScript Bitwise operators. TypeScript Assignment operators.

  18. Assign multiple variables to the same value in Javascript?

    The original variables you listed can be declared and assigned to the same value in a short line of code using destructuring assignment. The keywords let, const, and var can all be used for this type of assignment. let [moveUp, moveDown, moveLeft, moveRight, mouseDown, touchDown] = Array(6).fill(false); answered Jul 20, 2020 at 2:17.

  19. How to assign a multiline string literal to a variable?

    ES20xx supports spanning strings over multiple lines using template strings: let str = `This is a text with multiple lines. Escapes are interpreted, \n is a newline.`; let str = String.raw`This is a text with multiple lines. Escapes are not interpreted, \n is not a newline.`;

  20. TypeScript: Handbook

    Enums. Enums are one of the few features TypeScript has which is not a type-level extension of JavaScript. Enums allow a developer to define a set of named constants. Using enums can make it easier to document intent, or create a set of distinct cases. TypeScript provides both numeric and string-based enums.