Primitive Data Types in Typescript

Once you are familiar with What is a TypeScript, next step is to learn about its data type which is crucial part in any programming language. Following diagram illustrates data types which are categorised as Primitive Data Types/Built In Types and User Defined Types.

Data Types in Type Script

Let’s have a closer look at each type.

TypeScript Primitive Data Types

1. string: String data type is a one of the most used data types in any programming language. It represents sequence of characters which is either surrounded by single quotes (‘) or double quotes (“).

We can declare a variable with string data type in typescript as follows:

let stringVariableName : string;

Note that we have used let keyword which indicates this declaration is a block scope. Once we declared variable with specific data type, we can not assign another value which has different data type.

Like following assignment will throw an error:

stringVariableName = 123; //will throw an error

If you declare same variable in .js file instead of .ts file like var stringVariable = ‘typescript tutorials’; and assign stringVariable = 5; further in your code, it will not any error.

You can also declare variable without any data type assigned to it like,

let myVariable; //without any data type

Default this will have any type.

2. number: Number datatype is used to represent both values, integers and fractions. It also supports decimal, hexadecimal, binary and octal literals.

let numberVariableName : number;

3. boolean: This data type represents logical value, either true or false.
It can also store binary values as 0 and 1.

let booleanVariable : boolean = true;

4. void: This is a special primitive data type which represents there is no data. It is opposite of any datatype. void can also be used as a return type of function if its not returning any value.
We can only assign null or undefined value to variable which has void datatype.

let voidVariable: void = undefined;

5. null: It represents variable can take only null value. Its also useless like void because it will not accept other values rather than null.

let nullVariable: null = null;

6. undefined: It denotes variable can take only one value, that is undefined. It is used where variable value is not defined or initialized.

let undefinedVariable: undefined = undefined;

This is all about in built/ primitive datatypes which are quite simple.

User Defined Data Types: We have covered user defined data types in this typescript tutorial as it needs more attention compared to primitive data types.