TypeScript DataTypes


What is DataType in Programming Language?

A data type is used to assign a value to variable. Assigned value may be operational, logical, relational and mathematical type. When we assign any value to variable it should have the same types whatever we want to perform. Such as

  • Integer- Whole numbers or negative value
  • Boolean:-Representing logical values,
  • String: Alphanumeric characters

Variables

Variables are used to store multiple value in a program. It allocated memory in random order thereby making it difficult to read and retrieve the values in the order of their declaration. To declare variable there are some rules which should be follow:

  • Variable name should be alphabets and numeric digits.
  • It does not contains spaces and special characters with name.
  • Variable name can not start with digit name.
  • A variable must be declared first before use.

Variables Declation

Declare its type but no value. In this case, the variable will show undefined type in TypeScript.

[var] [identifier] : [type-annotation];

Declare its type and value in one statement.

[var] [identifier] : [type-annotation]=[value];

Typescript Data Types

TypeScript is a superset of JavaScript. So it supports all of the JavaScript types and also have some additional special types. JavaScript has eight data types. primitive types and one object Data type. The primitive types are number, string, boolean, symbol, undefined, and null. Everything else is an object in JavaScript. TypeScript brings its own special types are unknown, any, void & never.

data type Output

The data type classification is as given named below :

  1. Built in Types
  2. User defined types
  3. Special types

1. Built in Types

These are the predefined dataTypes which are not defined by the user. TypeScript supports the following basic built in types number, string, boolean, undefined, null and symbol.

Number

Number type is used to represent both integer and floating-point numbers as defined in below example. TypeScript also supports binary, hexadecimaland octal literals introduced in ECMAScript.

let CheckOne: number = 12.0;   // number   
  let CheckTwo: number = 0x37CF; // hexadecimal  
  let CheckThree: number = 0o377 ; // octal  
  let CheckFour: number = 0b111001; // binary    
  let CheckFive: number = 10.4; // float
  console.log(CheckOne);
  console.log(CheckTwo);
  console.log(CheckThree);
  console.log(CheckFour);
  console.log(CheckFive);

String

A string type works with textual data. It is a a string isa sequence of characters. A string that begins with a double quotes (") must end with a double quote.

 let checkstring:string="Rohatash Kumar";
  console.log(checkstring);

Boolean

The boolean type has two values true and false in lowercase. A boolean type stores true or false value. True and false value represents:

  • Zero -Represents corresponding value False
  • Non Zero -Represents corresponding value True
let CheckBooleantrue:boolean=true;
  let  CheckBooleanfalse:boolean=false;
  console.log(CheckBooleantrue);
  console.log(CheckBooleanfalse);

Undefined

By default when we declare a variable but not assigned any value. It assigned undefined value. It has only one value undefined. It means the value does not exist in the compiler.

// Undefined 
  let Checkundefined;
  console.log(Checkundefined);

Null

The null type is the second primitive data type that also has only one value null. null means no value or absence value. It need to assign null value with variable.

// null 
let Checknull=null;
console.log(Checknull);

Symbol

Symbol data type introduced with ES6 or ECMAScript 2015 in javascript. Symbols are immutable and unique. Symbol variables always return a new unique value. When we create two symbols with the same description as shown in below example. then they will be unique and immutable.

//Symbol
let CheckSymbol1= Symbol("Rohatash");
let CheckSymbol2 = Symbol("Rohatash");
console.log(CheckSymbol1==CheckSymbol2) //false

2. User Defined Type

User Defined Type are the types which are defined by user. TypeScript User-defined types included asEnumerations (enums), classes, interfaces, arrays, and tuple.

Array

An array is a collection of elements of the same data type such as numbers, strings. An array is a special variable which can hold collection of more than one value of similar type.

//Array
var CheckArray:string[]; 
CheckArray = ["Rohatash","Ritesh","Ravindar"] 
console.log(CheckArray[0]); 
console.log(CheckArray[1]);

Touples

Touples is just like apposite of array. It is used to store value of varied types. Array is not support that. So TypeScript defines a data type called tuple that helps to achieve such a purpose of store varies types.

// Tuples
var CheckTuple:string[]; 
CheckTuple = ["Rohatash","1","Ritesh","Ravindar"] 
console.log(CheckTuple[0]); 
console.log(CheckTuple[1]);

Class

A class in terms of OOP is a template which encapsulate methods and data members. A Class contains the following things: fields or variable, Constructorsand functions.

//Class
export class AppComponent 
{
  Fieldorvariable:string="Rohatash";
  constructor(){} 
  public Function():void{}
}

Interface

The interface contains only abstract or declaration ofmethodsand fields but not theimplementation of methods and fields.Interface defined as below:

interface Employee {
  id: number;
  firstName: string;
  lastName: string;
  getFullName(): string;
}

Implemention of interface function and feilds in class.

export class AppComponent implements Employee {
  id=1;
  firstName="Rohatash";
  lastName="Kumar";
  getFullName() {
   return this.firstName + ' ' + this.lastName;
   console.log(this.firstName + ' ' + this.lastName);   
   }
}
 

3. Special types

The TypeScript Type System brings its own special types other than JavaScript. They are unknown, any, void and never.

Any

As name suggested every type value can be store to any type. So any is the supertype of all the other types. The TS compiler to skip type checking at compile time.

 //Any 
let vAny:any=12; // We can assign anything to any 
let vAny1: string = "Rohatash"; // Any is assignable to anything 
console.log(vAny, vAny1);

Unknown

We can assign anything or varies data types to unknown just like any. We can assign unknown only with type any. Other data type can not assign unknown type except any. The below example explain it.

//unknown
let Checkunknown: unknown;
let Checkunknown1: unknown = Checkunknown;   // No error
let Checkunknown2: any = Checkunknown;       // No error
//let Checkunknown3: boolean = Checkunknown;   // Type 'unknown' is not assignable to type 'boolean'

Never

Never is information that this particular part shouldn't be never occur . It might be helpful for when we define it but value never occured.

For example,

public finderror(message: string): never 
{
  throw new Error(message);
}

Void

As name suggested when we define return type of a function avoid this type don't return any value, but they are reachable and they can be used not like never.


public Function():void{  
}
You can also check to run all the above code in one place:
import { Component } from '@angular/core';

  let CheckOne: number = 12.0;   // number   
  let CheckTwo: number = 0x37CF; // hexadecimal  
  let CheckThree: number = 0o377 ; // octal  
  let CheckFour: number = 0b111001; // binary    
  let CheckFive: number = 10.4; // float
  console.log(CheckOne);
  console.log(CheckTwo);
  console.log(CheckThree);
  console.log(CheckFour);
  console.log(CheckFive);
  //String
  let checkstring:string="Rohatash Kumar";
  console.log(checkstring);
  //Boolean
  let CheckBooleantrue:boolean=true;
  let  CheckBooleanfalse:boolean=false;
  console.log(CheckBooleantrue);
  console.log(CheckBooleanfalse);
// Undefined 
  let Checkundefined;
  console.log(Checkundefined);

// null 
let Checknull=null;
console.log(Checknull);

//Symbol
let CheckSymbol1= Symbol("Rohatash");
let CheckSymbol2 = Symbol("Rohatash");
console.log(CheckSymbol1==CheckSymbol2) //false

//Array
var CheckArray:string[]; 
CheckArray = ["Rohatash","Ritesh","Ravindar"] 
console.log(CheckArray[0]); 
console.log(CheckArray[1]);

// Tuples
var CheckTuple:string[]; 
CheckTuple = ["Rohatash","1","Ritesh","Ravindar"] 
console.log(CheckTuple[0]); 
console.log(CheckTuple[1]);

//Any 
let vAny:any=12; // We can assign anything to any 
let vAny1: string = "Rohatash"; // Any is assignable to anything 
console.log(vAny, vAny1);

//unknown
let Checkunknown: unknown;
let Checkunknown1: unknown = Checkunknown;   // No error
let Checkunknown2: any = Checkunknown;       // No error
//let Checkunknown3: boolean = Checkunknown;   // Type 'unknown' is not assignable to type 'boolean'

//Never
let Checknever: never;

interface Employee {
  id: number;
  firstName: string;
  lastName: string;
  getFullName(): string;
}

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements Employee {
  id=1;
  firstName="Rohatash";
  lastName="Kumar";
  getFullName() {
   return this.firstName + ' ' + this.lastName;
   console.log(this.firstName + ' ' + this.lastName);
   
   }
}

Output

data type Output


Prev Next