In TypeScript, the data types are useful to define a type of data the variable can hold such as number, string, boolean, etc. in our application. The TypeScript will support all the types that are supported by JavaScript.
As discussed, TypeScript is a strict type checking language so the compiler will associate the type to the variables at the time of variable initialization based on the value or defined type.
Following is the syntax of defining a type or data type to the variables in typescript.
[Keyword] [Variable Name]: [Data Type] = [Value];
[Keyword] [Variable Name]: [Data Type];
If you observe the above syntax, we added data type after the variable name to tell the compiler that the type of data the variable can hold or the type of variable that belongs to.
var
, let
or const
to define the scope and usage of variable.You need to remember that the data types part is optional while declaring and defining the variables in typescript. Now, we will learn how to use data types in TypeScript with examples.
Following is the example of defining the variables with required data types in typescript.
let uname: string = "Suresh Dasari"; // string
let ulocation: string = "Hyderabad"; // string
let age: number = 33; // number
let isCompleted: boolean = true; // boolean
console.log("Name:" + uname); // Suresh Dasari
console.log("Location:" + ulocation); // Hyderabad
console.log("Age:" + age); // 33
console.log("Is Completed:" + isCompleted); // true
If you observe the above TypeScript data types example, we defined multiple variables with different data types based on our requirements.
In typescript, different type of data types available, those are:
Type | Data Types |
---|---|
Primitive / Built-in Types | number, string, boolean, etc. |
User-defined / Object Types | array, tuple,enum, etc. |
Following diagram will illustrate more details about different data types in typescript.
If you observe the above diagram, the any
type is pointing to the both primitive and user-defined types because it is a super set of all the data types.
Following table lists the different type of built-in or primitive data types in typescript.
number | string | boolean |
void | null | undefined |
never | any |
Following table lists the different type of user-defined data types in typescript.
array | class | interface |
tuple | enum | function |
any |
In the next typescript chapters, we will learn about each data type in-detail with examples.