TypeScript - Variable

TypeScript follows the same rules as JavaScript for variable declarations. Variables can be declared using: var , let , and const .

Variables in TypeScript can be declared using var keyword, same as in JavaScript. The scoping rules remains the same as in JavaScript.

To solve problems with var declarations, ES6 introduced two new types of variable declarations in JavaScript, using the keywords let and const . TypeScript, being a superset of JavaScript, also supports these new types of variable declarations.

The let declarations follow the same syntax as var declarations. Unlike variables declared with var , variables declared with let have a block-scope. This means that the scope of let variables is limited to their containing block, e.g. function, if else block or loop block. Consider the following example.

In the above example, all the variables are declared using let. num3 is declared in the if block so its scope is limited to the if block and cannot be accessed out of the if block. In the same way, num4 is declared in the while block so it cannot be accessed out of while block. Thus, when accessing num3 and num4 else where will give a compiler error.

The same example with the var declaration is compiled without an error.

Advantages of using let over var

1) Block-scoped let variables cannot be read or written to before they are declared.

In the above example, the TypeScript compiler will give an error if we use variables before declaring them using let, whereas it won't give an error when using variables before declaring them using var.

2) Let variables cannot be re-declared

The TypeScript compiler will give an error when variables with the same name (case sensitive) are declared multiple times in the same block using let.

In the above example, the TypeScript compiler treats variable names as case sensitive. num is different than Num , so it won't give any error. However, it will give an error for the variables with the same name and case.

Variables with the same name and case can be declared in different blocks, as shown below.

Similarly, the compiler will give an error if we declare a variable that was already passed in as an argument to the function, as shown below.

Thus, variables declared using let minimize the possibilities of runtime errors, as the compiler give compile-time errors. This increases the code readability and maintainability.

Variables can be declared using const similar to var or let declarations. The const makes a variable a constant where its value cannot be changed. Const variables have the same scoping rules as let variables.

Const variables must be declared and initialized in a single statement. Separate declaration and initialization is not supported.

Const variables allow an object sub-properties to be changed but not the object structure.

Even if you try to change the object structure, the compiler will point this error out.

variable assignment typescript

We are a team of passionate developers, educators, and technology enthusiasts who, with their combined expertise and experience, create in -depth, comprehensive, and easy to understand tutorials.We focus on a blend of theoretical explanations and practical examples to encourages hands - on learning. Visit About Us page for more information.

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

How to dynamically assign properties to an object in TypeScript

variable assignment typescript

Editor’s note: This article was updated on 6 October 2023, introducing solutions like type assertions and the Partial utility type to address the TypeScript error highlighted.

How To Dynamically Assign Properties To An Object In TypeScript

JavaScript is a dynamically typed language, meaning that a variable’s type is determined at runtime and by what it holds at the time of execution. This makes it flexible but also unreliable and prone to errors because a variable’s value might be unexpected.

TypeScript, on the other hand, is a statically typed version of JavaScript — unlike JavaScript, where a variable can change types randomly, TypeScript defines the type of a variable at its declaration or initialization.

Dynamic property assignment is the ability to add properties to an object only when they are needed. This can occur when an object has certain properties set in different parts of our code that are often conditional.

In this article, we will explore some ways to enjoy the dynamic benefits of JavaScript alongside the security of TypeScript’s typing in dynamic property assignment.

Consider the following example of TypeScript code:

This seemingly harmless piece of code throws a TypeScript error when dynamically assigning name to the organization object:

An Error Is Thrown When Dynamically Assigning A Property To An Object

See this example in the TypeScript Playground .

The source of confusion, perhaps rightly justified if you’re a TypeScript beginner, is: how could something that seems so simple be such a problem in TypeScript?

The TL;DR of it all is that if you can’t define the variable type at declaration time, you can use the Record utility type or an object index signature to solve this. But in this article, we’ll go through the problem itself and work toward a solution that should work in most cases.

The problem with dynamically assigning properties to objects

Generally speaking, TypeScript determines the type of a variable when it is declared. This determined type stays the same throughout your application. There are exceptions to this rule, such as when considering type narrowing or working with the any type, but otherwise, this is a general rule to remember.

In the earlier example, the organization object is declared as follows:

There is no explicit type assigned to this variable, so TypeScript infers a type of organization based on the declaration to be {} , i.e., the literal empty object.

If you add a type alias, you can explore the type of organization :

Exploring The Literal Object Type

See this in the TypeScript Playground .

When you then try to reference the name prop on this empty object literal:

You receive the following error:

There are many ways to solve the TypeScript error here. Let’s consider the following:

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:

This eliminates any surprises. You’re clearly stating what this object type is and rightly declaring all relevant properties when you create the object.

However, this is not always feasible if the object properties must be added dynamically, which is why we’re here.

Solution 2: Use an object index signature

Occasionally, the properties of the object truly need to be added at a time after they’ve been declared. In this case, you can use the object index signature, as follows:

When the organization variable is declared, you can explicitly type it to the following: {[key: string] : string} .

You might be used to object types having fixed property types:

However, you can also substitute name for a “variable type.” For example, if you want to define any string property on obj :

Note that the syntax is similar to how you’d use a variable object property in standard JavaScript:

The TypeScript equivalent is called an object index signature.

variable assignment typescript

Over 200k developers use LogRocket to create better digital experiences

variable assignment typescript

Moreover, note that you could type key with other primitives:

Solution 3: Use the Record Utility Type

The Record utility type allows you to constrict an object type whose properties are Keys and property values are Type . It has the following signature: Record<Keys, Type> .

In our example, Keys represents string and Type . The solution here is shown below:

Instead of using a type alias, you can also inline the type:

Using The Record Utility Type

Solution 4: Use the Map data type

A Map object is a fundamentally different data structure from an object , but for completeness, you could eliminate this problem if you were using Map .

Consider the starting example rewritten to use a Map object:

With Map objects, you’ll have no errors when dynamically assigning properties to the object:

Dark Background Typescript Playground Showing Map Object No Errors

This seems like a great solution at first, but the caveat is your Map object is weakly typed. You can access a nonexisting property and get no warnings at all:

See the TypeScript Playground .

This is unlike the standard object. By default, the initialized Map has the key and value types as any — i.e., new () => Map<any, any> . Consequently, the return type of the s variable will be any :

Dark Background Typescript Playground Showing Constant S With Type Any Indicated By Red Arrow

When using Map , at the very least, I strongly suggest passing some type information upon creation. For example:

s will still be undefined, but you won’t be surprised by its code usage. You’ll now receive the appropriate type for it:

Dark Background Typescript Playground Showing Properly Typed Map Value With Const S With Type String Undefined Indicated By Red Arrow

If you truly don’t know what the keys of the Map will be, you can go ahead and represent this at the type level:

And if you’re not sure what the keys or values are, be safe by representing this at the type level:

Solution 5: Consider an optional object property

This solution won’t always be possible, but if you know the name of the property to be dynamically assigned, you can optionally provide this when initializing the object as shown below:

If you don’t like the idea of using optional properties, you can be more explicit with your typing as shown below:

Solution 6: Leveraging type assertions

TypeScript type assertion is a mechanism that tells the compiler the variable’s type and overrides what it infers from the declaration or assignment. With this, we are telling the compiler to trust our understanding of the type because there will be no type verification.

We can perform a type assertion by either using the <> brackets or the as keyword. This is particularly helpful with the dynamic property assignment because it allows the properties we want for our object to be dynamically set because TypeScript won’t enforce them.

Let’s take a look at applying type assertions to our problem case:

Dark Background Typescript Playground Showing Dynamic Property Assignment Using Type Assertion

Note that with type assertions, the compiler is trusting that we will enforce the type we have asserted. This means if we don’t, for example, set a value for organization.name , it will throw an error at runtime that we will have to handle ourselves.

Solution 7: Use the Partial utility type

TypeScript provides several utility types that can be used to manipulate types. Some of these utility types are Partial , Omit , Required , and Pick .

For dynamic property assignments, we will focus specifically on the Partial utility type. This takes a defined type and makes all its properties optional. Thus, we can initialize our object with any combination of its properties, from none to all, as each one is optional:

In our example with the Partial utility type, we defined our organization object as the type partial Org , which means we can choose not to set a phoneNumber property:

Dark Background Typescript Playground Showing Dynamic Property Assignment Using Utility Type Partial

Grouping and comparing the options for adding properties in TypeScript

In this article, we explored the different options for setting properties dynamically in TypeScript. These options can be grouped together by their similarities.

Index/Key signatures

This group of options allows you to define the type of keys allowed without limiting what possible keys can exist. The options in this group include:

  • Using an object index signature
  • Using the Record utility type
  • Using the Map data type (with key/value typing)

With these, we can define that our object will take string indexes and decide what types to support as values, like String , Number , Boolean , or Any :

See in TypeScript Playground .

Pro: The main benefit of these methods is the ability to dynamically add properties to an object while still setting expectations for the potential types of keys and values.

Con: The main disadvantage of this way of defining objects is that you can’t predict what keys our objects will have and so some references may or may not be defined. An additional disadvantage is that if we decide to define our key signature with type Any , then the object becomes even more unpredictable.

Conditional/Optional properties

This set of object assignment methods shares a common feature: the definition of optional properties. This means that the range of possible properties are known but some may or may not be set. The options in this group include:

  • Using optional object properties
  • Using the Partial utility type
  • Using type assertions

See this example in the TypeScript Playground , or in the code block below:

Note: While these options mean that the possible keys are known and may not be set, TypeScript’s compiler won’t validate undefined states when using type assertions. This can lead to unhandled exceptions during runtime. For example, with optional properties and the Partial utility type, name has type string or undefined . Meanwhile, with type assertions, name has type string .

Pro: The advantage of this group of options is that all possible object keys and values are known.

Con: The disadvantage is that while the possible keys are known, we don’t know if those keys have been set and will have to handle the possibility that they are undefined.

Apart from primitives, the most common types you’ll have to deal with are likely object types. In cases where you need to build an object dynamically, take advantage of the Record utility type or use the object index signature to define the allowed properties on the object.

If you’d like to read more on this subject, feel free to check out my cheatsheet on the seven most-asked TypeScript questions on Stack Overflow, or tweet me any questions . Cheers!

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 .

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

variable assignment typescript

Stop guessing about your digital experience with LogRocket

Recent posts:.

Automate Repetitive Tasks With The Pinion Code Generator

Automate repetitive tasks with the Pinion code generator

Discover how the Pinion code generator automates repetitive tasks and boosts productivity compared to tools like Yeoman, Plop, and Hygen.

variable assignment typescript

Exploring Hurl, a command line alternative to Postman

Hurl is an excellent Postman alternative that improves the DX of working with APIs through the command line.

variable assignment typescript

How to integrate WunderGraph with your frontend application

Unify and simplify APIs using WunderGraph to integrate REST, GraphQL, and databases in a single endpoint.

variable assignment typescript

Understanding the latest Webkit features in Safari 17.4

The Safari 17.4 update brought in many modern features and bug fixes. Explore the major development-specific updates you should be aware of.

variable assignment typescript

3 Replies to "How to dynamically assign properties to an object in TypeScript"

I know this is explicitly for TypeScript, and I think type declarations should always be first. But in general, you can also use a Map object. If it’s really meant to by dynamic, might as well utilize the power of Map.

Great suggestion (updated the article). It’s worth mentioning the weak typing you get by default i.e., with respect to Typescript.

Hi, thanks for your valuable article please consider ‘keyof type’ in TypeScript, and add this useful solution if you are happy have nice time

Leave a Reply Cancel reply

variable assignment typescript

Variables and Types

In TypeScript, variables are containers for storing data values. TypeScript enhances variables with type annotations, allowing you to enforce the type of data your variables can hold. This helps in catching type-related errors early in the development process, making your code more robust and maintainable. There are several basic types in TypeScript, including:

  • number : For numeric values.
  • string : For textual data.
  • boolean : For true/false values.
  • any : A wildcard type that can be anything.
  • arrays : For collections of values, denoted by Type[] or Array<Type> .

Defining a variable is done in TypeScript can be done either using a type or omitting it. If omitted, the interpreter will set the type according to the type of variable it was defined with.

TypeScript has a very strong typing system. One of the more useful features of it is that it allows you to define a variable to hold a specific range of types.

For example, to create a variable that can hold either null or a number, use the following notation:

When declaring variables, TypeScript uses let and const keywords from modern JavaScript:

  • let : Declares a block-scoped variable, optionally initializing it to a value. let variables can be reassigned.
  • const : Declares a block-scoped constant. Once assigned, const variables cannot be reassigned.

Declaring Variables

Using let :

When you use let , you're telling TypeScript that the variable may change its value over time. For example:

Using const :

With const , the variable must be initialized at the time of declaration, and it cannot be reassigned later. This is useful for values that should not change throughout the application.

TypeScript is statically typed. This means that the type of a variable is known at compile time. This is different from JavaScript, where types are understood dynamically at runtime.

Basic Types

Here are some basic types in TypeScript:

Number : All numbers in TypeScript are floating-point values. These can be integers, decimals, etc.

String : Represents a sequence of characters. TypeScript, like JavaScript, uses double quotes ( " ) or single quotes ( ' ) to surround string data.

Boolean : The most basic datatype is the simple true/false value.

Any : It can be any type of value. It is useful when you don't want to write a specific type, but its use should be limited to when you really don't know what type there will be.

Understanding these basics will help you to declare variables and types effectively in TypeScript, leading to more predictable and error-resistant code.

Given the provided code, identify the errors in variable declarations based on TypeScript types and fix them.

variable assignment typescript

Coding for Kids is an online interactive tutorial that teaches your kids how to code while playing!

Receive a 50% discount code by using the promo code:

Start now and play the first chapter for free, without signing up.

variable assignment typescript

  • 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 Variables & Constants Tutorial

In this TypeScript tutorial we learn about temporary data containers called variables and constants that store values in memory when the app runs.

We learn how to declare and initialize variables and constants, how to use them and how to change variable values.

Laslty we discuss operands, lvalues and rvalues and the difference between the var and the let keywords.

  • What is a variable

How to declare a variable

How to assign a value to a variable, how to initialize a variable with a value, how to use a variable, how to change the value of a variable.

  • What is a constant

How to initialize and use a constant

  • Operands: lvalues and rvalues
  • Var vs Let: What's the difference

Summary: Points to remember

A variable is a temporary data container that stores a value in memory while the application is running.

Consider a calculator app. When we perform an addition for example, the app stores the result in a variable which we can use to perform additional calculations.

In the example above, the letters ‘x’ and ‘y’ store the resulting data from the arithmetic.

Variables are used all over our apps to store runtime data. When the app is closed, or the variable is no longer used by the program, the value in memory is removed.

To create a variable without a value, we use one of TypeScript’s special keywords, var . This is known as variable declaration.

We can create the variable in one of two ways, with a type, or without.

We can also use the let keyword to declare a variable.

We’ll talk about the difference between the two in a little bit.

As an example, let’s define a variable called msg1 of type string and a variable called msg2 that doesn’t have a type.

Now that we have variables, we can store values in them. This is known as assignment.

To assign a value to a variable, we write the name of the variable, followed by the = (equals) operator and lastly, the value we want to store.

note We don’t use the var or let keywords. The variable already exists, we’re just adding a value to it.

In the example above we use our two variables from before and assign short strings to them.

The msg2 variable wasn’t declared with a type, but when we assigned a value to it, the compiler automatically inferred the type of string because the value we assigned was a string.

We don’t have to declare a variable and assign a value to it afterwards, we can do both in a single step. This is known as initialization.

This time for the example, let’s assign values directly to the variables when we declare them.

To use a variable, we simply refer to its identifier wherever we need to use it in our code.

In the example above, we initialize two variables with numbers, then add them together and store the result in another variable.

Then, we print them all to the console with the console.log() function.

Variables in TypeScript are mutable, which means we can change their values while the application is running (at runtime).

To change the value of a variable, we simply assign it a new one with the assignment operator.

This time we change the value of result by performing a different calculation.

When we compile and run the script, we see on the second line that the value has changed.

A constant is a variable that cannot have it’s value changed during runtime.

We use constants when we do not want a value to accidentally change, like the value of Pi, or gravity.

A constant cannot be declared without a value because a value cannot be assigned later on, and there would be no point to an empty constant.

To initialize a constant with a value, we use the const keyword.

tip As we mentioned in our Basic Syntax lesson, the convention for naming constants is all uppercase letters with multiple words separated with underscores.

In the example above, we declare two constants for values that we don’t want to change while the script runs. Then we use them all over the script just like we would a variable.

tip Constants are the same as variables, except their values are immutable, they cannot change during runtime.

TypeScript has two types of expressions, lvalues and rvalues.

The operand on the left side of the = (assignment operator) is the Lvalue, and the operand on the right side is the Rvalue.

An Lvalue can have a value assigned to it so it’s allowed to appear either on the left or the right side of an assignment.

An rvalue cannot have a value assigned to it so it may only appear on the right side of an assignment.

The important difference between var and let is that let can only be used in a local scope.

Let’s see an example, then explain what’s happening.

In the example above, we define a local scope with the curly braces of the if statement and initialize the variable a inside.

When we try try to use a outside of the curly braces in the second console.log() function, the compiler raises an error.

The error states that it cannot find the name a . That’s because the second console.log() function doesn’t know that a exists, it can’t see inside the curly braces.

If we change the keyword from let to var , we are allowed to use a outside of the if statement’s scope.

This time, the compiler doesn’t raise an error and if we run the script, it will print the value twice.

  • Variables and Constants are temporary data containers.
  • We can specify a type for our variables and constants or we may omit it.
  • The var or let keywords can be used to declare or initialize a variable.
  • The const keyword is used to initialize a constant.
  • Constants can only be initialized with a value, not declared empty.
  • Values stored in variables are mutable.
  • Values stored in constants are immutable.
  • To use a variable or constant, we simply refer to its name.
  • Declare a variable
  • Assign a value to a variable
  • Initialize a variable with a value
  • Use a variable
  • Change the value of a variable
  • Initialize and use a constant

Popular Articles

  • Build Tools (May 21, 2024)
  • Useful Packages (May 21, 2024)
  • Linting (May 21, 2024)
  • Non Nullable (May 21, 2024)
  • Formatting (May 21, 2024)

TypeScript Variable

Switch to English

Table of Contents

Introduction

Variable declaration in typescript, types of variables in typescript, differences between var, let and const keywords, tips, tricks and common error-prone cases.

  • Declaration of variables in TypeScript is almost the same as in JavaScript. The key difference lies in the addition of type annotation, which makes TypeScript a strongly typed language.
  • TypeScript uses 'var', 'let', and 'const' keywords for variable declaration.
  • TypeScript provides several data types for declaring variables. These include:
  • 'var' keyword: Variables declared with 'var' are function-scoped or globally scoped, not block-scoped. They can be re-declared and updated.
  • 'let' keyword: Variables declared with 'let' are block-scoped. They can be updated but not re-declared.
  • 'const' keyword: Variables declared with 'const' are also block-scoped. However, they cannot be updated nor re-declared.
  • Always use 'let' or 'const' for variable declaration to avoid scope issues associated with the 'var' keyword. This is because 'let' and 'const' are block-scoped, while 'var' is not.
  • Ensure that the type assigned to a variable matches the type annotation during declaration. TypeScript will throw an error if there's a mismatch.
  • If a variable is declared but not initialized, TypeScript will infer it as 'any' type. However, it's a best practice to always include a type annotation.
  • For 'const' variables, ensure that they are initialized at the time of declaration. TypeScript throws an error if a 'const' variable is declared but not initialized.

Variable Declaration

let and const are two relatively new concepts for variable declarations in JavaScript. As we mentioned earlier , let is similar to var in some respects, but allows users to avoid some of the common “gotchas” that users run into in JavaScript.

const is an augmentation of let in that it prevents re-assignment to a variable.

With TypeScript being an extension of JavaScript, the language naturally supports let and const . Here we’ll elaborate more on these new declarations and why they’re preferable to var .

If you’ve used JavaScript offhandedly, the next section might be a good way to refresh your memory. If you’re intimately familiar with all the quirks of var declarations in JavaScript, you might find it easier to skip ahead.

var declarations

Declaring a variable in JavaScript has always traditionally been done with the var keyword.

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:

and we can also access those same variables within other functions:

In this above example, g captured the variable a declared in f . At any point that g gets called, the value of a will be tied to the value of a in f . Even if g is called once f is done running, it will be able to access and modify a .

Scoping rules

var declarations have some odd scoping rules for those used to other languages. Take the following example:

Some readers might do a double-take at this example. The variable x was declared within the if block , and yet we were able to access it from outside that block. That’s because var declarations are accessible anywhere within their containing function, module, namespace, or global scope - all which we’ll go over later on - regardless of the containing block. Some people call this var -scoping or function-scoping . Parameters are also function scoped.

These scoping rules can cause several types of mistakes. One problem they exacerbate is the fact that it is not an error to declare the same variable multiple times:

Maybe it was easy to spot out for some experienced JavaScript developers, but the inner for -loop will accidentally overwrite the variable i because i refers to the same function-scoped variable. As experienced developers know by now, similar sorts of bugs slip through code reviews and can be an endless source of frustration.

Variable capturing quirks

Take a quick second to guess what the output of the following snippet is:

For those unfamiliar, setTimeout will try to execute a function after a certain number of milliseconds (though waiting for anything else to stop running).

Ready? Take a look:

Many JavaScript developers are intimately familiar with this behavior, but if you’re surprised, you’re certainly not alone. Most people expect the output to be

Remember what we mentioned earlier about variable capturing? Every function expression we pass to setTimeout actually refers to the same i from the same scope.

Let’s take a minute to consider what that means. setTimeout will run a function after some number of milliseconds, but only after the for loop has stopped executing; By the time the for loop has stopped executing, the value of i is 10 . So each time the given function gets called, it will print out 10 !

A common work around is to use an IIFE - an Immediately Invoked Function Expression - to capture i at each iteration:

This odd-looking pattern is actually pretty common. The i in the parameter list actually shadows the i declared in the for loop, but since we named them the same, we didn’t have to modify the loop body too much.

let declarations

By now you’ve figured out that var has some problems, which is precisely why let statements were introduced. Apart from the keyword used, let statements are written the same way var statements are.

The key difference is not in the syntax, but in the semantics, which we’ll now dive into.

Block-scoping

When a variable is declared using let , it uses what some call lexical-scoping or block-scoping . Unlike variables declared with var whose scopes leak out to their containing function, block-scoped variables are not visible outside of their nearest containing block or for -loop.

Here, we have two local variables a and b . a ’s scope is limited to the body of f while b ’s scope is limited to the containing if statement’s block.

Variables declared in a catch clause also have similar scoping rules.

Another property of block-scoped variables is that they can’t be read or written to before they’re actually declared. While these variables are “present” throughout their scope, all points up until their declaration are part of their temporal dead zone . This is just a sophisticated way of saying you can’t access them before the let statement, and luckily TypeScript will let you know that.

Something to note is that you can still capture a block-scoped variable before it’s declared. The only catch is that it’s illegal to call that function before the declaration. If targeting ES2015, a modern runtime will throw an error; however, right now TypeScript is permissive and won’t report this as an error.

For more information on temporal dead zones, see relevant content on the Mozilla Developer Network .

Re-declarations and Shadowing

With var declarations, we mentioned that it didn’t matter how many times you declared your variables; you just got one.

In the above example, all declarations of x actually refer to the same x , and this is perfectly valid. This often ends up being a source of bugs. Thankfully, let declarations are not as forgiving.

The variables don’t necessarily need to both be block-scoped for TypeScript to tell us that there’s a problem.

That’s not to say that a block-scoped variable can never be declared with a function-scoped variable. The block-scoped variable just needs to be declared within a distinctly different block.

The act of introducing a new name in a more nested scope is called shadowing . It is a bit of a double-edged sword in that it can introduce certain bugs on its own in the event of accidental shadowing, while also preventing certain bugs. For instance, imagine we had written our earlier sumMatrix function using let variables.

This version of the loop will actually perform the summation correctly because the inner loop’s i shadows i from the outer loop.

Shadowing should usually be avoided in the interest of writing clearer code. While there are some scenarios where it may be fitting to take advantage of it, you should use your best judgement.

Block-scoped variable capturing

When we first touched on the idea of variable capturing with var declaration, we briefly went into how variables act once captured. To give a better intuition of this, each time a scope is run, it creates an “environment” of variables. That environment and its captured variables can exist even after everything within its scope has finished executing.

Because we’ve captured city from within its environment, we’re still able to access it despite the fact that the if block finished executing.

Recall that with our earlier setTimeout example, we ended up needing to use an IIFE to capture the state of a variable for every iteration of the for loop. In effect, what we were doing was creating a new variable environment for our captured variables. That was a bit of a pain, but luckily, you’ll never have to do that again in TypeScript.

let declarations have drastically different behavior when declared as part of a loop. Rather than just introducing a new environment to the loop itself, these declarations sort of create a new scope per iteration . Since this is what we were doing anyway with our IIFE, we can change our old setTimeout example to just use a let declaration.

and as expected, this will print out

const declarations

const declarations are another way of declaring variables.

They are like let declarations but, as their name implies, their value cannot be changed once they are bound. In other words, they have the same scoping rules as let , but you can’t re-assign to them.

This should not be confused with the idea that the values they refer to are immutable .

Unless you take specific measures to avoid it, the internal state of a const variable is still modifiable. Fortunately, TypeScript allows you to specify that members of an object are readonly . The chapter on Interfaces has the details.

let vs. const

Given that we have two types of declarations with similar scoping semantics, it’s natural to find ourselves asking which one to use. Like most broad questions, the answer is: it depends.

Applying the principle of least privilege , all declarations other than those you plan to modify should use const . The rationale is that if a variable didn’t need to get written to, others working on the same codebase shouldn’t automatically be able to write to the object, and will need to consider whether they really need to reassign to the variable. Using const also makes code more predictable when reasoning about flow of data.

Use your best judgement, and if applicable, consult the matter with the rest of your team.

The majority of this handbook uses let declarations.

Destructuring

Another ECMAScript 2015 feature that TypeScript has is destructuring. For a complete reference, see the article on the Mozilla Developer Network . In this section, we’ll give a short overview.

Array destructuring

The simplest form of destructuring is array destructuring assignment:

This creates two new variables named first and second . This is equivalent to using indexing, but is much more convenient:

Destructuring works with already-declared variables as well:

And with parameters to a function:

You can create a variable for the remaining items in a list using the syntax ... :

Of course, since this is JavaScript, you can just ignore trailing elements you don’t care about:

Or other elements:

Tuple destructuring

Tuples may be destructured like arrays; the destructuring variables get the types of the corresponding tuple elements:

It’s an error to destructure a tuple beyond the range of its elements:

As with arrays, you can destructure the rest of the tuple with ... , to get a shorter tuple:

Or ignore trailing elements, or other elements:

Object destructuring

You can also destructure objects:

This creates new variables a and b from o.a and o.b . Notice that you can skip c if you don’t need it.

Like array destructuring, you can have assignment without declaration:

Notice that we had to surround this statement with parentheses. JavaScript normally parses a { as the start of block.

You can create a variable for the remaining items in an object using the syntax ... :

Property renaming

You can also give different names to properties:

Here the syntax starts to get confusing. You can read a: newName1 as ” a as newName1 ”. The direction is left-to-right, as if you had written:

Confusingly, the colon here does not indicate the type. The type, if you specify it, still needs to be written after the entire destructuring:

Default values

Default values let you specify a default value in case a property is undefined:

In this example the b? indicates that b is optional, so it may be undefined . keepWholeObject now has a variable for wholeObject as well as the properties a and b , even if b is undefined.

Function declarations

Destructuring also works in function declarations. For simple cases this is straightforward:

But specifying defaults is more common for parameters, and getting defaults right with destructuring can be tricky. First of all, you need to remember to put the pattern before the default value.

The snippet above is an example of type inference, explained earlier in the handbook.

Then, you need to remember to give a default for optional properties on the destructured property instead of the main initializer. Remember that C was defined with b optional:

Use destructuring with care. As the previous example demonstrates, anything but the simplest destructuring expression is confusing. This is especially true with deeply nested destructuring, which gets really hard to understand even without piling on renaming, default values, and type annotations. Try to keep destructuring expressions small and simple. You can always write the assignments that destructuring would generate yourself.

The spread operator is the opposite of destructuring. It allows you to spread an array into another array, or an object into another object. For example:

This gives bothPlus the value [0, 1, 2, 3, 4, 5] . Spreading creates a shallow copy of first and second . They are not changed by the spread.

You can also spread objects:

Now search is { food: "rich", price: "$$", ambiance: "noisy" } . Object spreading is more complex than array spreading. Like array spreading, it proceeds from left-to-right, but the result is still an object. This means that properties that come later in the spread object overwrite properties that come earlier. So if we modify the previous example to spread at the end:

Then the food property in defaults overwrites food: "rich" , which is not what we want in this case.

Object spread also has a couple of other surprising limits. First, it only includes an objects’ own, enumerable properties . Basically, that means you lose methods when you spread instances of an object:

Second, the TypeScript compiler doesn’t allow spreads of type parameters from generic functions. That feature is expected in future versions of the language.

© 2012-2021 Microsoft Licensed under the Apache License, Version 2.0. https://www.typescriptlang.org/docs/handbook/variable-declarations.html

  • 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 Tutorial

TypeScript Basics

  • Introduction to TypeScript
  • Difference between TypeScript and JavaScript
  • How to install TypeScript ?
  • Hello World in TypeScript
  • How to execute TypeScript file using command line?

Variables in TypeScript

  • What are the different keywords to declare variables in TypeScript ?
  • Identifiers and Keywords in TypeScript

TypeScript primitive types

  • Data types in TypeScript
  • TypeScript Numbers
  • TypeScript String
  • Explain the concept of null and its uses in TypeScript

TypeScript Object types

  • What are TypeScript Interfaces?
  • TypeScript class
  • How enums works in TypeScript ?
  • TypeScript Tuples

TypeScript other types

  • What is any type, and when to use it in TypeScript ?
  • How to Create an Object in Typescript ?
  • What is an unknown type and when to use it in TypeScript ?
  • Explain the purpose of never type in TypeScript

TypeScript combining types

  • TypeScript Union
  • What are type aliases and how to create it in Typescript ?

TypeScript Assertions

  • Explain Type assertions in TypeScript

TypeScript Functions

  • How to write a function in Typescript ?
  • How to achieve function overloading in TypeScript ?
  • Explain the arrow function syntax in TypeScript
  • TypeScript | toPrecision() Function
  • TypeScript | toFixed() Function
  • TypeScript | toLocaleString() Function
  • TypeScript | toString() Function

TypeScript interfaces and aliases

Typescript classes.

  • How to Extend an Interface from a class in TypeScript ?
  • How to use getters/setters in TypeScript ?
  • TypeScript Inheritance
  • When to use interfaces and when to use classes in TypeScript ?
  • Generics Interface in typescript
  • How to use property decorators in TypeScript ?

TypeScript modules

  • What are the Modules in Typescript ?
  • How to import a module in Typescript ?
  • TypeScript Arrays
  • TypeScript | Array push() Method
  • TypeScript Array slice() Method
  • TypeScript Array splice() Method
  • TypeScript Array reverse() Method
  • TypeScript Array reduce() Method
  • TypeScript Array concat() Method
  • TypeScript Array some() Method
  • TypeScript | Array shift() Method
  • TypeScript | Array map() Method
  • TypeScript | Array indexOf() Method
  • Array filter() Method - TypeScript
  • TypeScript | Array reduceRight() Method
  • TypeScript | Array join() Method
  • TypeScript | Array unshift() Method
  • TypeScript | Array sort() Method
  • TypeScript | Array lastIndexOf() Method
  • TypeScript | Array pop() Method
  • TypeScript | Array forEach() Method
  • TypeScript Array toString() Method

Typescript String

  • TypeScript | String Constructor Property
  • TypeScript String toLowerCase() Method
  • TypeScript String toString() Method
  • TypeScript | String toLocaleUpperCase() Method
  • TypeScript | String substring() Method
  • TypeScript | String substr() Method
  • TypeScript String split() Method
  • TypeScript | String valueOf() Method
  • TypeScript | String replace() Method
  • TypeScript | String toLocaleLowerCase() Method
  • TypeScript | String lastIndexOf() Method
  • TypeScript | String slice() Method with example
  • TypeScript | String concat() Method
  • TypeScript | String indexOf() Method
  • TypeScript | String Length Property
  • TypeScript | String search() Method
  • TypeScript String Prototype Property
  • TypeScript | String charCodeAt() Method

TypeScript Exercises

  • TypeScript Exercises, Practice Questions and Solutions

The variable is a named place in memory where some data/value can be stored. They serve as containers for storing data values, allowing to store numeric , string , boolean , and other types of information. In this TypeScript Variable Article, we’ll learn how to declare, manipulate, and utilize variables in TypeScript.

Variable Declaration in TypeScript

1. var, let, and const.

In TypeScript, we have three primary keywords for variable declaration:

  • var : Traditionally used in JavaScript, it has some quirks and scoping rules that can lead to unexpected behaviour. Variables declared with var are accessible anywhere within their containing function, module, namespace, or global scope.
  • let : Introduced to address the limitations of var, let provides block-scoping. It allows you to declare variables that are confined to specific blocks of code (such as loops or conditional statements). This helps prevent accidental variable redeclaration and enhances code clarity.
  • const : Similar to let, const also has block-scoping. However, it goes a step further by preventing re-assignment after initialization. Once you assign a value to a const variable, you cannot change it. Use const for values that should remain constant throughout your program.

2. Rules have to be followed:

  • Variable names can contains alphabets both Upper-case as well as Lower-case and digits also.
  • Variable names can’t start with a digit.
  • We can use _ and $ special characters only, apart from these other special characters are not allowed.

3. Ways to Variable declaration:

We can declare a variable in multiple ways like below:

  • var Identifier:Data-type = value;
  • var Identifier: Data-type;
  • var Identifier = value;
  • var Identifier;

3.  Type Annotations

TypeScript enhances variables with type annotations, making it a strongly typed language. When declaring a variable, you can specify its type explicitly. 

4. Variable scopes in TypeScript:

Here scope means the visibility of variable. The scope defines that we are able to access the variable or not. TypeScript variables can be of the following scopes:

  • Local Scope: As the name specified, are declared within the block like methods, loops etc. Local variables are accessible only within the construct where they are declared.
  • Global Scope: If the variable is declared outside the construct then we can access the variable anywhere. This is known as Global Scope.
  • Class Scope: If a variable is declared inside the class then we can access that variable within the class only.

Please Login to comment...

Similar reads.

author

  • JavaScript-Questions
  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

How to Update Variables & Properties in TypeScript

Avatar

By squashlabs, Last Updated: October 13, 2023

How to Update Variables & Properties in TypeScript

Setting a Value in TypeScript

Setting the value of a variable in typescript, setting the value of an object property in typescript, updating a value in typescript, setting the value of a property in typescript, changing a value in typescript, setting a value to null in typescript, setting a value to undefined in typescript, setting a value to a boolean in typescript, setting a value to a number in typescript, external sources.

Table of Contents

In TypeScript, you can set a value to a variable or property using the = operator. This allows you to assign a specific value to a variable or change the value of an existing variable. Let’s take a look at some examples:

Example 1: Setting a value to a variable

In this example, we declare a variable name of type string and assign the value “John” to it. We then log the value of the name variable to the console, which will output “John”.

Example 2: Setting a value to a property

In this example, we define a class Person with a property name of type string . We then create an instance of the Person class and set the value of the name property to “John”. Finally, we log the value of the name property to the console, which will output “John”.

Related Article: How to Implement and Use Generics in Typescript

To set the value of a variable in TypeScript , you can use the = operator followed by the desired value. Let’s look at an example:

In this example, we declare a variable age of type number and assign the value 25 to it. We then log the value of the age variable to the console, which will output 25.

To set the value of an object property in TypeScript , you can use the = operator followed by the desired value. Let’s see an example:

In this example, we define an object person with properties name and age . We initially set the value of the name property to “John” and the value of the age property to 25. Then, we update the value of the name property to “Jane”. Finally, we log the updated value of the name property to the console, which will output “Jane”.

To update a value in TypeScript, you can simply assign a new value to the variable or property. Let’s take a look at an example:

Example 1: Updating a value of a variable

In this example, we declare a variable age of type number and assign the initial value 25 to it. We then log the value of the age variable to the console, which will output 25. After that, we update the value of the age variable to 30 and log it again, which will output 30.

Example 2: Updating a value of an object property

In this example, we define an object person with properties name and age . We initially set the value of the age property to 25. We then log the value of the age property to the console, which will output 25. After that, we update the value of the age property to 30 and log it again, which will output 30.

Related Article: Tutorial: Navigating the TypeScript Exit Process

In TypeScript, you can set the value of a property using the = operator. This allows you to assign a specific value to a property or change the value of an existing property. Let’s take a look at an example:

In this example, we define a class Person with properties name and age . We then create an instance of the Person class and set the values of the name and age properties. Finally, we log the values of the name and age properties to the console, which will output “John” and 25, respectively.

To change a value in TypeScript , you can simply assign a new value to the variable or property. Let’s see an example:

Example 1: Changing the value of a variable

In this example, we declare a variable age of type number and assign the initial value 25 to it. We then log the value of the age variable to the console, which will output 25. After that, we change the value of the age variable to 30 and log it again, which will output 30.

Example 2: Changing the value of an object property

In this example, we define an object person with properties name and age . We initially set the value of the age property to 25. We then log the value of the age property to the console, which will output 25. After that, we change the value of the age property to 30 and log it again, which will output 30.

In TypeScript, you can set a value to null to indicate the absence of an object or the intentional assignment of a null value. Let’s see an example:

In this example, we declare a variable person that can hold a value of type string or null . We initially assign the value “John” to the person variable and log it to the console, which will output “John”. After that, we set the value of the person variable to null and log it again, which will output null .

Related Article: Tutorial on TypeScript Dynamic Object Manipulation

In TypeScript, you can set a value to undefined to indicate the absence of a value or the intentional assignment of an undefined value. Let’s see an example:

In this example, we declare a variable age that can hold a value of type number or undefined . Initially, the value of the age variable is undefined , and when logged to the console, it will output undefined . We then set the value of the age variable to 25 and log it again, which will output 25. Finally, we set the value of the age variable to undefined and log it again, which will output undefined .

In TypeScript, you can set a value to a boolean using the = operator followed by either true or false . Let’s see an example:

In this example, we declare a variable isRaining of type boolean and assign the value true to it. We then log the value of the isRaining variable to the console, which will output true . After that, we assign the value false to the isRaining variable and log it again, which will output false .

To set a value to a number in TypeScript , you can use the = operator followed by a numeric value. Let’s look at an example:

Related Article: Tutorial: Checking Enum Value Existence in TypeScript

Here are some external sources for further reading:

– TypeScript Documentation: https://www.typescriptlang.org/docs/

Squash: a faster way to build and deploy Web Apps for testing

  Cloud Dev Environments

  Test/QA enviroments

  Staging

One-click preview environments for each branch of code.

More Articles from the Typescript Tutorial: From Basics to Advanced Concepts series:

Tutorial: converting string to bool in typescript.

TypeScript is a powerful language that allows developers to write type-safe code for JavaScript applications. One common task in TypeScript is converting strings to... read more

Tutorial: Converting a String to Boolean in TypeScript

Converting a TypeScript string into a boolean can be a tricky task. This tutorial provides different approaches, code snippets, and best practices for handling this... read more

Tutorial on Prisma Enum with TypeScript

Prisma Enum is a powerful feature in TypeScript that allows you to define and use enumerated types in your Prisma models. This tutorial will guide you through the... read more

How Static Typing Works in TypeScript

TypeScript is a powerful programming language that offers static typing capabilities for better code quality. In this comprehensive guide, we will explore various... read more

Tutorial: Loading YAML Files in TypeScript

Loading YAML files in TypeScript is an essential skill for developers working with configuration data. This tutorial provides a comprehensive guide on how to load YAML... read more

How to Check If a String is in an Enum in TypeScript

A detailed guide on how to check if a string is part of an Enum in TypeScript. This article covers topics such as defining an Enum, checking if a string is in an Enum,... read more

Variables & Data Types in TypeScript (Live Playground)

In this tutorial, we will explore variables and data types in TypeScript. Understanding how to declare variables and specify their data types is crucial for writing clean, maintainable, and type-safe TypeScript code.

Variables ​

In TypeScript, you can declare variables using the let and const keywords:

  • let : Use let to declare variables that can be reassigned later.
  • const : Use const to declare variables that cannot be reassigned after their initial assignment. Here's an example of using let and const :

Data Types ​

TypeScript provides several built-in data types, which we will cover below:

1. number ​

The number data type is used for both integers and floating-point numbers:

2. string ​

The string data type represents textual data:

3. boolean ​

The boolean data type represents true or false values:

To declare an array, use the Array type followed by the element type in angle brackets, or use the element type followed by square brackets:

Tuples are fixed-length arrays with known, but potentially different, types:

Enums are a way to define named constants for numeric values:

The any data type represents any JavaScript value, effectively opting out of type checking for a variable:

The void data type is used to indicate that a function does not return any value:

Conclusion ​

In this tutorial, we have explored variables and data types in TypeScript. Understanding how to declare variables with appropriate data types and type annotations is essential for writing clean, maintainable, and type-safe TypeScript code. In the upcoming tutorials, we will dive deeper into other TypeScript concepts and features, such as functions, classes, interfaces, and more.

variable assignment typescript

Learn TypeScript

  • Introduction to Typescript What is Typescript and Why Should You Learn It?
  • Setting Up a Typescript Development Environment
  • Basic Typescript Syntax and Types
  • Types and Variables in Typescript Understanding the Different Types in Typescript (e.g. Number, String, Boolean)

Declaring and Initializing Variables in Typescript

  • Type Inference and Type Annotations
  • The "any" Type and Why It Should Be Used with Caution
  • Interfaces and Classes in Typescript Understanding the Difference Between Interfaces and Classes in Typescript
  • Defining Interfaces and Implementing Them in Classes
  • Extending Interfaces and Classes
  • Access Modifiers (Public, Private, Protected) in Typescript
  • Functions in Typescript Declaring Functions in Typescript
  • Function Return Types and Parameter Types
  • Optional and Default Parameters in Typescript Functions
  • Rest Parameters in Typescript Functions
  • Generics in Typescript Understanding Generics and Why They are Useful
  • Declaring and Using Generics in Functions, Classes, and Interfaces
  • Constraining Generics with Type Parameters
  • Advanced Typescript Features Enums in Typescript
  • Decorators in Typescript
  • Namespaces in Typescript
  • Modules in Typescript
  • Working with Typescript in the Real World Integrating Typescript with Popular JavaScript Libraries and Frameworks (e.g. React, Angular)
  • Best Practices for Using Typescript in a Project
  • Tips and Tricks for Debugging Typescript Code

Participants 966

variable assignment typescript

Yasin Cakal

Welcome to the “Declaring and Initializing Variables in TypeScript” section of our course “Learn TypeScript”! In this article, we will cover the various ways you can declare and initialize variables in TypeScript, including using the “let” and “const” keywords, destructuring, and the spread operator. By the end of this article, you should have a good understanding of these concepts and be able to use them effectively in your TypeScript programs.

Declaring Variables with “let” and “const”

TypeScript has two keywords for declaring variables: “let” and “const”. The “let” keyword is used to declare variables that can be reassigned later, while the “const” keyword is used to declare variables that cannot be reassigned. For example:

In this example, the variable “x” is declared using the “let” keyword and can be reassigned, while the variable “y” is declared using the “const” keyword and cannot be reassigned.

It is generally a good idea to use “const” for variables that you do not need to change, as it helps to prevent accidental reassignments and makes your code easier to understand. However, there may be cases where you need to use “let”, such as when you are using a loop variable or when you need to reassign a variable based on some condition.

Destructuring

TypeScript supports destructuring, which allows you to extract values from arrays and objects and assign them to separate variables. For example:

In this example, we are using destructuring to extract values from an array and an object and assign them to separate variables. The variables “a”, “b”, and “c” are assigned the values from the array “arr”, while the variables “x” and “y” are assigned the values from the object “obj”.

Destructuring is a convenient way to extract values from arrays and objects, especially when you need to extract multiple values at once. It is also useful for creating variables with more descriptive names, as shown in the example above where we used “x” and “y” to represent the x and y coordinates of an object.

Spread Operator

TypeScript also supports the spread operator (…), which allows you to expand an array or object into separate values. For example:

In this example, we are using the spread operator to expand the array “arr” and the object “obj” into separate values. The array “arr2” is created by adding the values from “arr” and the additional values 4 and 5, while the object “obj2” is created by adding the values from “obj” and the additional value “z”.

The spread operator is useful for creating new arrays and objects based on existing ones, or for combining multiple arrays or objects into a single one. It is also useful for creating shallow copies of arrays and objects, as the spread operator creates a new array or object rather than modifying the original one.

In conclusion, this article has covered the various ways you can declare and initialize variables in TypeScript, including using the “let” and “const” keywords, destructuring, and the spread operator. You should now have a good understanding of these concepts and be able to use them effectively in your TypeScript programs. In future sections of our course, we will cover more advanced topics, such as type inference and the “var” keyword, and how to use them to write more concise and maintainable TypeScript code.

To review these concepts, we will go through a series of exercises designed to test your understanding and apply what you have learned.

What is the difference between the “let” and “const” keywords in TypeScript?

The “let” keyword is used to declare variables that can be reassigned later, while the “const” keyword is used to declare variables that cannot be reassigned. It is generally a good idea to use “const” for variables that you do not need to change, as it helps to prevent accidental reassignments and makes your code easier to understand. However, there may be cases where you need to use “let”, such as when you are using a loop variable or when you need to reassign a variable based on some condition.

How do you extract values from an array or object using destructuring in TypeScript?

To extract values from an array or object using destructuring in TypeScript, you can use the following syntax:

How do you expand an array or object into separate values using the spread operator in TypeScript?

To expand an array or object into separate values using the spread operator in TypeScript, you can use the following syntax:

How can you create a shallow copy of an array or object using the spread operator in TypeScript?

To create a shallow copy of an array or object using the spread operator in TypeScript, you can use the following syntax:

In this example, we are using the spread operator to expand the array “arr” and the object “obj” into separate values, which are then assigned to the new variables “arr2” and “obj2”. The spread operator creates a new array or object rather than modifying the original one, so “arr2” and “obj2” are shallow copies of “arr” and “obj”.

What are some benefits of using destructuring and the spread operator in TypeScript?

There are several benefits to using destructuring and the spread operator in TypeScript:

  • Destructuring allows you to extract values from arrays and objects and assign them to separate variables, which can be more convenient and easier to read than accessing the values directly.
  • The spread operator allows you to expand an array or object into separate values, which is useful for creating new arrays and objects based on existing ones or for combining multiple arrays or objects into a single one.
  • Both destructuring and the spread operator can help you write more concise and maintainable TypeScript code, as they allow you to write less boilerplate code and focus more on the logic of your program.
  • Read Tutorial
  • Watch Guide Video

In this guide we're going to get into how to use variables in typescript. There are three types of variables that we're going to be able to use and I'm going to walk through each one of them and then afterwards I'm going to show you what some of the differences are.

Variable Types

So the three types are var, let, and const. Var and let are very similar if you are used to JavaScript programming then var is probably one of the ones that you're most used to. However in the last few years let has also become popular and there's a pretty subtle difference but it is an important difference to know when working with these two and I’ll go into an example of how they're different shortly. But first to declare variables in typescript you simply type in whatever type of variable you're doing such as var. Then you give the name so say fullName and an important thing with typescript is to make sure that you're using camel case. So if you were coming from the Ruby language or something like that this variable would probably look like this because Ruby uses snake case. However in typescript in JavaScript you want to follow the style guide in the style guide for these is to use camel case just like this. So I'm going to declare the name then give a colon. Followed by that data type.

So I'm going to make a full name, which is of the string data type, and inside of this I'm going to pass a string so I pass in my name and then a semi colon at the very end.

With let, it's the exact same thing. So I'm going to say pretending this is an e-commerce program or something I say pay to count. And the data type for this one is going to be a boolean and then I'm going to say that it is true.

Now const is short for constant which means that this is a value that you're placing in declaring the inside of your program and you're letting JavaScript know that you do not want this value to be changed. Pretty much every language has a constant variable type. However they get treated differently. For example in Ruby you can actually change your constants. It's considered a bad practice but because we're be so flexible it will let you do that. Typescript is not that flexible in. You'll see in a second what happens when I try to change a constant value. So for this one I'm going to say version number is set this equal to the data type of number and let's get this equal to 1.3.

Now as you notice as I was typing typescript and really sublime text was constantly giving me underlines on when I had a syntax error or anything like that which is very nice and handy. So now I just want to create some console log statements. So I’m just going to say console log and I'm going to put in these values as a full name. Paid account and then version number.

Now I'm not going to walk through this on in every single video because I'd probably get monotonous. However make sure that you change your tsconfig.json file because it's only going to run the files that you have listed here. So before the video I changed to the file so that's calling these 006_variables.ts file you can have it call any of the ones that you have. But before I had it running the 005 file and anything that you want to run make sure that you include it here in the array. Now I've saved the file and if I switch to the terminal I have to type in tsc to compile everything to JavaScript. And after I've done that by type ls –a this is going to show me all the files and you can see that we have now our 006_variables , JavaScript file, and a map file. So now I just have to type in node 006_variables and if I hit run you can see that this all worked perfectly. So that's good.

So now that you know how to create variables let's actually get into what makes them different because each one of these is a little bit different in some form or another. So I'm going to come down here and I'm going to redefine each one of these. So I'm going to say full name and set it equal to “Tiffany Hudgens”

And then create these ones as well so I'll say paidAccount and it is a Boolean which is a reason why it's giving me this error so I’m going to change this to false.

Then versionNumber here I’ll change to 1.4

Now I can't even run this program. And the reason why is because I am trying to redefine a constant. I'm trying to reset a constant. And if I click on where it's shown me have a syntax error you can see where it says down on the bottom that a left hand side of assignment expression cannot be a constant. So what it's saying there is you created a constant. You can't change the value of it. So now if I simply get rid of this change in versionNumber and re run the tsc command. Then re run the file with node you can see that this is working. It reset the values of the var in the left variables but it did not touch the constant. So that is the difference between a constant and a var and a let.

Now there's a much more subtle difference between var and let, in terms of how they work in a program. I'm going to create a basic function and I'm first going to comment all this out. So you'll have access to it in the show notes but it won't interfere with the rest of the program. So I'm going to create a basic function and don't worry we're going to get into functions in more detail later on. So I'm going to create a printName function and just pass in two arguments which is going to be first and the last name and inside of the function I'm going to create or declare a variable.

So I'm going to create one and call it greeting it's of type string and inside of this. Say “hi there” comma and then give a semi colon. Now I'm going to create a console log statement and inside of this I'm going to pass in greeting and I'm going to do some string interpellation so I'm going to say first followed by a space and followed by the last name. And now if I go in and then I also have to call the function so call print name and pass and Jordan and then Hudgens the semi semicolon at the end. Now if I run tsc and then run the file you can see that the function prints it out. My first and last name right after I gave the greeting.

Now if I change this to let. And I re run everything again. You can see everything still works perfectly.

So there is no difference on that side. But now where the difference occurs is when I do something like this. So if I copy all of this and I have this let statement here in both spots so I have let greeting and let greeting and I try to change this and say hey there in this one. It's not going to let me do that and it's going to throw an error. And that's because you are not allowed to redefine a let statement.

You can reset the value so I could do something like this. I could set a greeting and then change that. Now if I run this code. You'll see that this still works perfectly.

But now where it's a little bit different is if I change this to var and I copy that duplicate it one you can see that there is no error. So this is letting us redefine everything.

And you may wonder why that's a big deal. Part of the reason why it's such a big deal is because what if I actually change this to number and change of that value here you can see that this is now given an error.

So it's very important is when you're redefining this is make sure that you are you're only allowed to redefine it if you're using the same data type. So let me. If we hover over if we click on it's going to say subsequent variable declarations must have the same type. So variable greeting must be of type string but here as type number.

So if I fix this. And I change this one back to Hey there this is still going to work. You can see that works even though I'm re declaring it. But now if I hit Let you're going to get a different kind of error message you're not getting the same one about the data type that's only specific to VAR's and now you're getting one that says can't re declare block scoped variable grading. So that's really where the difference comes down to is where and when you have a block scoped item such as a variable with a lead. It's a very specific on how you can declare that where with var you have more flexibility. This is something that comes in handy. The more you get into angular development and so I wanted to really point out what those key differences were they may seem subtle and in a very simplistic program they're not going to matter at all. However once you get into things like working with big data management or anything like that the difference between and var actually becomes much more important and also hopefully you can see some of the power with typescript in the fact that It also caught when I change the data type with var because in other languages that are more loose with that would never be a problem. But the issue is that it actually can lead to a lot of bugs I imagine in Ruby program where you have a variable. You set it equal to a string and then somewhere down the line you actually change the data type on accident and you set it equal to an integer or vice versa. That program is still going to run you're not going to get any errors until you try to call one of those variables and then pass a method to it. What this does is it gives you a little bit of data protection on that because it doesn't even let the program run with that kind of system in place. So here I'm just going to get rid of this change back to var and the whole program will run just like normally.

So that is an introduction to how to use variables. The VAR let in console variables along with what some of the subtle differences are between each one.

  • Source code

devCamp does not support ancient browsers. Install a modern version for best experience.

This page has been deprecated

This handbook page has been replaced, go to the new page

Basic Types

For programs to be useful, we need to be able to work with some of the simplest units of data: numbers, strings, structures, boolean values, and the like. In TypeScript, we support the same types as you would expect in JavaScript, with an extra enumeration type thrown in to help things along.

The most basic datatype is the simple true/false value, which JavaScript and TypeScript call a boolean value.

As in JavaScript, all numbers in TypeScript are either floating point values or BigIntegers. These floating point numbers get the type number , while BigIntegers get the type bigint . In addition to hexadecimal and decimal literals, TypeScript also supports binary and octal literals introduced in ECMAScript 2015.

Another fundamental part of creating programs in JavaScript for webpages and servers alike is working with textual data. As in other languages, we use the type string to refer to these textual datatypes. Just like JavaScript, TypeScript also uses double quotes ( " ) or single quotes ( ' ) to surround string data.

You can also use template strings , which can span multiple lines and have embedded expressions. These strings are surrounded by the backtick/backquote ( ` ) character, and embedded expressions are of the form ${ expr } .

This is equivalent to declaring sentence like so:

TypeScript, like JavaScript, allows you to work with arrays of values. Array types can be written in one of two ways. In the first, you use the type of the elements followed by [] to denote an array of that element type:

The second way uses a generic array type, Array<elemType> :

Tuple types allow you to express an array with a fixed number of elements whose types are known, but need not be the same. For example, you may want to represent a value as a pair of a string and a number :

When accessing an element with a known index, the correct type is retrieved:

Accessing an element outside the set of known indices fails with an error:

A helpful addition to the standard set of datatypes from JavaScript is the enum . As in languages like C#, an enum is a way of giving more friendly names to sets of numeric values.

By default, enums begin numbering their members starting at 0 . You can change this by manually setting the value of one of its members. For example, we can start the previous example at 1 instead of 0 :

Or, even manually set all the values in the enum:

A handy feature of enums is that you can also go from a numeric value to the name of that value in the enum. For example, if we had the value 2 but weren’t sure what that mapped to in the Color enum above, we could look up the corresponding name:

We may need to describe the type of variables that we do not know when we are writing an application. These values may come from dynamic content – e.g. from the user – or we may want to intentionally accept all values in our API. In these cases, we want to provide a type that tells the compiler and future readers that this variable could be anything, so we give it the unknown type.

If you have a variable with an unknown type, you can narrow it to something more specific by doing typeof checks, comparison checks, or more advanced type guards that will be discussed in a later chapter:

In some situations, not all type information is available or its declaration would take an inappropriate amount of effort. These may occur for values from code that has been written without TypeScript or a 3rd party library. In these cases, we might want to opt-out of type checking. To do so, we label these values with the any type:

The any type is a powerful way to work with existing JavaScript, allowing you to gradually opt-in and opt-out of type checking during compilation.

Unlike unknown , variables of type any allow you to access arbitrary properties, even ones that don’t exist. These properties include functions and TypeScript will not check their existence or type:

The any will continue to propagate through your objects:

After all, remember that all the convenience of any comes at the cost of losing type safety. Type safety is one of the main motivations for using TypeScript and you should try to avoid using any when not necessary.

void is a little like the opposite of any : the absence of having any type at all. You may commonly see this as the return type of functions that do not return a value:

Declaring variables of type void is not useful because you can only assign null (only if strictNullChecks is not specified, see next section) or undefined to them:

Null and Undefined

In TypeScript, both undefined and null actually have their types named undefined and null respectively. Much like void , they’re not extremely useful on their own:

By default null and undefined are subtypes of all other types. That means you can assign null and undefined to something like number .

However, when using the strictNullChecks flag, null and undefined are only assignable to unknown , any and their respective types (the one exception being that undefined is also assignable to void ). This helps avoid many common errors. In cases where you want to pass in either a string or null or undefined , you can use the union type string | null | undefined .

Union types are an advanced topic that we’ll cover in a later chapter.

As a note: we encourage the use of strictNullChecks when possible, but for the purposes of this handbook, we will assume it is turned off.

The never type represents the type of values that never occur. For instance, never is the return type for a function expression or an arrow function expression that always throws an exception or one that never returns. Variables also acquire the type never when narrowed by any type guards that can never be true.

The never type is a subtype of, and assignable to, every type; however, no type is a subtype of, or assignable to, never (except never itself). Even any isn’t assignable to never .

Some examples of functions returning never :

object is a type that represents the non-primitive type, i.e. anything that is not number , string , boolean , bigint , symbol , null , or undefined .

With object type, APIs like Object.create can be better represented. For example:

Generally, you won’t need to use this.

Type assertions

Sometimes you’ll end up in a situation where you’ll know more about a value than TypeScript does. Usually, this will happen when you know the type of some entity could be more specific than its current type.

Type assertions are a way to tell the compiler “trust me, I know what I’m doing.” A type assertion is like a type cast in other languages, but it performs no special checking or restructuring of data. It has no runtime impact and is used purely by the compiler. TypeScript assumes that you, the programmer, have performed any special checks that you need.

Type assertions have two forms.

One is the as -syntax:

The other version is the “angle-bracket” syntax:

The two samples are equivalent. Using one over the other is mostly a choice of preference; however, when using TypeScript with JSX, only as -style assertions are allowed.

A note about let

You may have noticed that so far, we’ve been using the let keyword instead of JavaScript’s var keyword which you might be more familiar with. The let keyword is actually a newer JavaScript construct that TypeScript makes available. You can read in the Handbook Reference on Variable Declarations more about how let and const fix a lot of the problems with var .

About Number , String , Boolean , Symbol and Object

It can be tempting to think that the types Number , String , Boolean , Symbol , or Object are the same as the lowercase versions recommended above. These types do not refer to the language primitives however, and almost never should be used as a type.

Instead, use the types number , string , boolean , object and symbol .

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 ❤

Ryan Cavanaugh  (53)

Last updated: May 21, 2024  

variable assignment typescript

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

variable assignment typescript

Variable 'X' is used before being assigned in TypeScript

avatar

Last updated: Feb 28, 2024 Reading time · 4 min

banner

# Variable 'X' is used before being assigned in TypeScript

The error "Variable is used before being assigned" occurs when we declare a variable without assigning a value to it or we only assign a value if a condition is met.

To solve the error, change the variable's type to possibly undefined or give it an initial value.

Here are 3 examples of how the error occurs.

The first two examples cause the error because:

  • We declare a variable and set its type.
  • We don't give an initial value to the variable.
  • We try to use the variable.

# Initialize the variable to solve the error

To solve the error, give the variable an initial value of the expected type when declaring it.

initializing the variable to solve the error

We declared the variables with initial values so we aren't using them before they are assigned anymore.

# Update the variable's type to be possibly undefined

An alternative solution is to update the variable's type to possibly undefined .

update variable type to be possibly undefined

We used a union type to specify that the variables can either be one type or be undefined .

Now we have to use an if statement as a type guard to make sure the variable isn't undefined before we add a property or an element to it.

With arrays, there is no real benefit to doing this. It's best to just assign an empty array to the variable when declaring it and type the variable correctly.

# Using the Partial utility type to solve the error

If you're working with objects and you aren't able to set default values for all properties, consider using the Partial utility type .

The type can be used to set the object's properties to optional.

You can then give the variable an initial value of an empty object .

using partial utility type to solve the error

The Partial utility type is used to set all of the properties of the Employee type to optional, so we can give the employee variable an initial value of an empty object.

# Assigning a value to a variable only if a condition is met

The error is often caused when we only assign a value to a variable if a certain condition is met.

We can update the variable's type to be possibly undefined to resolve the issue.

The salary variable could be a number or it could be undefined .

Now that we've set its type accurately, the error no longer occurs.

Alternatively, you could give the variable an initial value when declaring it.

Which approach you pick will depend on your use case. I prefer using initial values of the expected type if possible.

# Additional Resources

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

  • Argument of type not assignable to parameter type 'never'
  • Type 'string or undefined' is not assignable to type string
  • The left-hand side of assignment expression may not be an optional property access
  • Type 'string' is not assignable to type in TypeScript
  • Type 'undefined' is not assignable to type in TypeScript

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

  • skip navigation All Products Product Bundles DevCraft All Telerik .NET tools and Kendo UI JavaScript components in one package. Now enhanced with: NEW : Design Kits for Figma

How to Implement Function Overloading in TypeScript

' title=

Function overloading is a TypeScript feature that lets us define a function that accepts different kinds of arguments.

TypeScript mainly adds data type-checking capabilities that are missing in JavaScript. This makes programming easier since we don’t have to check the data type of variables and other values ourselves.

We can write our JavaScript programs in TypeScript. Then we can compile the TypeScript code into JavaScript so it can be run by JavaScript runtimes like the browser and Node.js.

One useful feature that is available in TypeScript is function overloading. Function overloading is a feature that lets us define a function that accepts different kinds of arguments.

In this article, we will look at how to implement function overloading in our TypeScript code.

Function Overloading in TypeScript

With TypeScript, we can define a function that accepts different kinds of arguments with function overloading.

To use this, we just have to add all the possible signatures for a function for the combinations of arguments we want the function to accept.

For example, to implement function overloading in TypeScript, we can write something like the following:

We have two different signatures for the add function and they both have a return type set to number .

The first signature expects that both parameters a and b are numbers. And the second signature expects that both parameters a and b are strings.

To implement the function, we make a and b accept the unknown type, which lets us pass in anything for a and b .

In the function body, we check the data types of a and b with the typeof operator. If a and b are both strings, we convert a and b to numbers with the Number function and then get the sum of the numbers. If they’re both numbers, then we just return the sum of them. Otherwise, we return 0.

The unknown type is a type-safe counterpart of any . We can’t assign values with unknown type to any variable. But we can convert unknown type values to something else that matches the type of the variable.

With the typeof checks, we narrowed the types of a and b to one data type so TypeScript can infer the type and do the operations for the variables with the inferred type.

Then we can call add by writing:

We call add with the values that are expected by at least one of the signatures, so it passes the type checks done by the TypeScript compiler.

If we call add with values that aren’t expected by any of the signatures like:

Then the TypeScript compiler will raise a type-check error.

The function implementation’s signature must be more general than the overload signatures. This way, the function with overloads can accept different kinds of values expected by at least one of the signatures.

Method Overloading

We can also overload constructor or class methods.

For instance, we can write something like:

We define the Greeter class with the greet method in it. The greet method is overloaded with two different signatures. The first takes a string and returns a string . The second takes a string array and also returns a string .

In the implementation, we make the person function have an unknown type. We can add a return type or omit it since the TypeScript compiler can infer the return type from the implementation. We can check the value of person in the implementation with our own type checks.

First we check if person is a string with typeof person === "string" . Then we check if person is an array with Array.isArray .

Next, we can create a Greeter instance and call the greet method by writing:

We create a Greeter instance with new . And then we call greet on the instance either with a string or an array of strings we specified with the signatures.

When to Use Function Overloading?

Ideally, we use function overloading only when we expect required arguments that have different types.

The examples above all have required parameters only but they’re allowed to have different types. If we expect some arguments that are optional, then we can use the optional parameter syntax instead.

For instance, instead of writing something like:

We can replace the overloads with optional parameters by writing something like:

Since we accept param1 and param2 as optional parameters, we can use ? to denote them as such.

Function overloading is a feature in TypeScript that lets us define a function that accepts different kinds of arguments.

We can use function overloading for specifying any kinds of function parameters. But ideally, we use them only for required parameters since TypeScript already has a simple optional function parameters syntax.

We can have function overloads for regular functions and class methods.

' title=

John Au-Yeung

John Au-Yeung is a frontend developer with 6+ years of experience. He is an avid blogger (visit his site at https://thewebdev.info/ ) and the author of Vue.js 3 By Example .

Related Posts

How my team accidentally moved to typescript and loved it, fully typed with trpc, pattern matching with typescript, all articles.

  • ASP.NET Core
  • ASP.NET MVC
  • ASP.NET AJAX
  • Blazor Desktop/.NET MAUI
  • Design Systems
  • Document Processing
  • Accessibility

variable assignment typescript

Latest Stories in Your Inbox

Subscribe to be the first to get our expert-written articles and tutorials for developers!

All fields are required

Loading animation

Progress collects the Personal Information set out in our Privacy Policy and the Supplemental Privacy notice for residents of California and other US States and uses it for the purposes stated in that policy.

You can also ask us not to share your Personal Information to third parties here: Do Not Sell or Share My Info

By submitting this form, I understand and acknowledge my data will be processed in accordance with Progress' Privacy Policy .

I agree to receive email communications from Progress Software or its Partners , containing information about Progress Software’s products. I understand I may opt out from marketing communication at any time here or through the opt out option placed in the e-mail communication received.

By submitting this form, you understand and agree that your personal data will be processed by Progress Software or its Partners as described in our Privacy Policy . You may opt out from marketing communication at any time here or through the opt out option placed in the e-mail communication sent by us or our Partners.

We see that you have already chosen to receive marketing materials from us. If you wish to change this at any time you may do so by clicking here .

Thank you for your continued interest in Progress. Based on either your previous activity on our websites or our ongoing relationship, we will keep you updated on our products, solutions, services, company news and events. If you decide that you want to be removed from our mailing lists at any time, you can change your contact preferences by clicking here .

COMMENTS

  1. 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() {.

  2. TypeScript Variable Declarations: var, let, const

    To solve problems with var declarations, ES6 introduced two new types of variable declarations in JavaScript, using the keywords let and const. TypeScript, being a superset of JavaScript, also supports these new types of variable declarations. Example: Variable Declaration using let. let employeeName = "John";

  3. How do I dynamically assign properties to an object in TypeScript

    Here is a special version of Object.assign, that automatically adjusts the variable type with every property change. No need for additional variables, type assertions, explicit types or object copies: ... dynamically assign properties to an object in TypeScript. to do that You just need to use typescript interfaces like so: interface IValue ...

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

    TypeScript, on the other hand, is a statically typed version of JavaScript — unlike JavaScript, where a variable can change types randomly, TypeScript defines the type of a variable at its declaration or initialization. Dynamic property assignment is the ability to add properties to an object only when they are needed.

  5. Variables and Types

    In TypeScript, variables are containers for storing data values. TypeScript enhances variables with type annotations, allowing you to enforce the type of data your variables can hold. ... // this is not allowed in TypeScript numberOrNull = "invalid assignment"; When declaring variables, TypeScript uses let and const keywords from modern ...

  6. TypeScript Variables & Constants Tutorial

    TypeScript Variables & Constants Tutorial. ... In the example above we use our two variables from before and assign short strings to them. The msg2 variable wasn't declared with a type, but when we assigned a value to it, the compiler automatically inferred the type of string because the value we assigned was a string.

  7. Understanding TypeScript Variables: A Comprehensive Guide

    Declaration of variables in TypeScript is almost the same as in JavaScript. The key difference lies in the addition of type annotation, which makes TypeScript a strongly typed language. TypeScript uses 'var', 'let', and 'const' keywords for variable declaration. The above code snippet declares three variables: 'name', 'age', and 'country' with ...

  8. Variable Declaration

    Variable Declaration. let and const are two relatively new concepts for variable declarations in JavaScript.As we mentioned earlier, let is similar to var in some respects, but allows users to avoid some of the common "gotchas" that users run into in JavaScript.. const is an augmentation of let in that it prevents re-assignment to a variable.. With TypeScript being an extension of ...

  9. Variables in TypeScript

    In this TypeScript Variable Article, we'll learn how to declare, manipulate, and utilize variables in TypeScript. ... However, it goes a step further by preventing re-assignment after initialization. Once you assign a value to a const variable, you cannot change it. Use const for values that should remain constant throughout your program. 2 ...

  10. How to Update Variables & Properties in TypeScript

    Setting the Value of a Variable in TypeScript. To set the value of a variable in TypeScript, you can use the = operator followed by the desired value. Let's look at an example: Example: let age: number; age = 25; console.log(age); // Output: 25 In this example, we declare a variable age of type number and assign the value

  11. Variables & Data Types in TypeScript (Live Playground)

    In TypeScript, you can declare variables using the let and const keywords: let: Use let to declare variables that can be reassigned later. const: Use const to declare variables that cannot be reassigned after their initial assignment. Here's an example of using let and const: TypeScript. let age: number = 25; const message: string = 'Hello ...

  12. Declaring and Initializing Variables in Typescript Code of Code

    TypeScript has two keywords for declaring variables: "let" and "const". The "let" keyword is used to declare variables that can be reassigned later, while the "const" keyword is used to declare variables that cannot be reassigned. For example: let x: number = 10; x = 20; // valid const y: number = 10; y = 20; // invalid.

  13. How to Use Variables in TypeScript

    var greeting : string = "Hi there, "; console.log(greeting + f + " " + l); } printName("Jordan", "Hudgens"); So I'm going to create one and call it greeting it's of type string and inside of this. Say "hi there" comma and then give a semi colon. Now I'm going to create a console log statement and inside of this I'm going to ...

  14. TypeScript Variables: Understanding Types and Declarations

    In this TypeScript tutorial, we'll be taking a closer look at variables and their types. As a beginner, understanding the basics of variables is crucial to g...

  15. TypeScript: Handbook

    Array. TypeScript, like JavaScript, allows you to work with arrays of values. Array types can be written in one of two ways. In the first, you use the type of the elements followed by [] to denote an array of that element type: let list: number[] = [1, 2, 3]; The second way uses a generic array type, Array<elemType>:

  16. Assigning Types to Variables

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

  17. JavaScript OR (||) variable assignment explanation

    This is made to assign a default value, in this case the value of y, if the x variable is falsy. The boolean operators in JavaScript can return an operand, and not always a boolean result as in other languages. The Logical OR operator ( ||) returns the value of its second operand, if the first one is falsy, otherwise the value of the first ...

  18. Variable 'X' is used before being assigned in TypeScript

    We declared the variables with initial values so we aren't using them before they are assigned anymore. # Update the variable's type to be possibly undefined. An alternative solution is to update the variable's type to possibly undefined.

  19. Best Way for Conditional Variable Assignment

    There are two methods I know of that you can declare a variable's value by conditions. Method 1: If the condition evaluates to true, the value on the left side of the column would be assigned to the variable. If the condition evaluates to false the condition on the right will be assigned to the variable. You can also nest many conditions into ...

  20. How to Implement Function Overloading in TypeScript

    We can't assign values with unknown type to any variable. But we can convert unknown type values to something else that matches the type of the variable. With the typeof checks, we narrowed the types of a and b to one data type so TypeScript can infer the type and do the operations for the variables with the inferred type. Then we can call ...

  21. How to specify type in variable assignment via an object in typescript

    I have variable assignments like: const { namespace, service, version, status } = req.query; How can I specify the types above to each of the variables? Neither of the following work: const { namespace as string } = req.query;, nor const { namespace:string } = req.query;. Its very weird to write as later:

  22. Specify type of variable after initial assignment in TypeScript

    Specify type of variable after initial assignment in TypeScript. Ask Question Asked 7 years ago. Modified 7 years ago. ... Is there any way to accomplish this without TypeScript complaining about the type not containing the right properties? Or, is there a way to reassign/specify the type of data from A | B to A or B?