Page Content

Tutorials

How do I Declare a Variable in TypeScript?

Variable in TypeScript

A fundamental idea in TypeScript is variable declaration, which combines the optional static type system of TypeScript with the variable declaration syntax of JavaScript (var, let, and const). JavaScript’s typed superset, TypeScript, compiles to standard JavaScript. The type annotation is the main tool TypeScript utilises to improve variable safety.

Syntax and the Role of Type Annotations

In TypeScript, you must insert a colon (:) after the variable name and the desired type in order to declare a variable with an explicit type annotation.

In general, the syntax is shown as:

var variableName: VariableType = initialValue;

A variable can be declared in a number of ways:

  1. Declaration with type and initial value: var name:string=”mary”.
  2. Declaration with type only:  The variable’s value is set to undefined by default, and it is explicitly typed.
  3. Declaration with initial value only (Inferred Typing):  The data type of the initial value is used to infer the type of the variable.
  4. Declaration with neither type nor initial value:  By default, the variable’s value is set to undefined and its data type is set to any.

Two important functions of type annotations are to help developers who are reading the code understand the inputs and outputs and to enable compile-time type checking, which enables the compiler to identify errors before the script is executed.

By requiring that the types supplied on each side of the assignment operator match, TypeScript enforces strong typing. An error is produced by the TypeScript compiler if you try to assign a value that is incompatible with the defined type.

As an illustration:

var num: number = 5;
num = "this is a string"; // error: Type 'string' is not assignable to type 'number'

During compilation, the compiler reports this problem. It is crucial to keep in mind that these type annotations are exclusive to TypeScript and only present at the static, compile-time level; they are removed when the code is built into JavaScript.

The Keywords

JavaScript’s variable declaration keywords (var) are supported by TypeScript, which also adds block-scoped keywords from ECMAScript 6 (let and const).

Function Scoping

Traditionally, variables declared with var in JavaScript are function scoped, as opposed to block scoped in many other languages (such C# or Java). This can lead to frequent mistakes because a block, which is indicated by curly brackets ({}), doesn’t produce a new variable scope.

Examine the following examples of legacy JavaScript behaviour using var:

var foo = 123;
if (true) {
var foo = 456;
}
console.log(foo);

The JavaScript result of the aforementioned code would be 456 since the variable foo inside the if block is the same as the variable outside of it.

Block Scoping

To give true block scope, TypeScript and ES6 added the let keyword. By reducing unexpected behaviour, let makes code easier to read and lowers the likelihood of programming errors. Whenever possible, let is the recommended method.

Block scoping is demonstrated in the identical case by using let:

let foo = 123;
if (true) {
let foo = 456; // This creates a new, local 'foo' restricted to the 'if' block
}
console.log(foo);

Since the inner foo in this instance is a distinct element unrelated to the variable defined outside the scope, the output is 123. In loops, this keyword is very helpful because it guarantees that the variable is distinct for every iteration.

Immutability and Literal Types

In order to specify variables as immutable, the const keyword is an important feature. Both documentation and runtime safety are improved by it.

TypeScript’s type inference is an important consideration when using const. A variable’s type is inferred by TypeScript as the literal value itself, rather than just the primitive type, when it is declared as const and given a literal value (such as a particular string or number).

When declaring a certain string, for instance:

const philosopher = "Hypatia";

TypeScript defines philosopher type as the literal "Hypatia" even though it is a string. A let declaration, which normally widens the type to the universal primitive (string), is not the same as this.

Index