In TypeScript, the type of a variable is denoted using :<type> annotation where <type> is any valid data type. Unlike programming languages like C and C++ in which the type of a variable is declared before the variable name like int a or void someFunc(), in TypeScript, the type annotation comes after the variable name, also known as the postfix type notation.

let fruit:string = 'Mango';

In the above program, :string signifies that the variable fruit contains string data. If you are claustrophobic, you can add space between the colon and the data type, like let fruit: **string** which is generally preferred.

(intro.ts)

In the above example, we have defined a few variables. Some of these variables have an initial value such as agecar and canDrive while others such as person do not.

TypeScript allows undefined or null as the value for a variable even though its type might say something else. For example, person variable can hold only string data but its value is undefined at the beginning. Similarly, age can hold only number data but it was initialized with the null value.

You can also override a variable with undefined or null value after it declared at any given moment. TypeScript considers undefined and null as the Null values or empty values. Though null and undefined are types in itself as we will learn in a bit, TypeScript doesn’t allow a variable to be Null (empty) by default.

To disable this behavior, we need to set strictNullChecks compiler-option to true. This will instruct the TypeScript compiler to disallow variables to hold undefined or null value. In this mode, the variable must hold a value of its type before consumption.

#web-development #javascript #programming #typescript #nodejs

TypeScript — Basic Types
1.20 GEEK