The TypeScript language accommodates various value types. It offers data types that enable JavaScript to evolve into a strongly typed programming language. While JavaScript lacks built-in support for data types, TypeScript allows us to leverage this feature within JavaScript. TypeScript is particularly significant for object-oriented programmers seeking to implement type features in any scripting or object-oriented programming language. The Type System verifies the correctness of the provided values prior to their utilization in the program, ensuring that the code performs as intended.
TypeScript offers data types through an optional type system. The classification of TypeScript data types can be outlined as follows.
1. Static Types
Within the realm of type systems, static types refer to "during compilation" or "prior to program execution." In a language with static typing, the types of variables, parameters, and objects are established and known to the compiler at compile time. The compiler utilizes this data to conduct type checking.
Static types can be classified into two additional subcategories:
Built-in or Primitive Type
TypeScript includes five fundamental data types, listed as follows.
Number
Similar to JavaScript, all numerical values in TypeScript are represented as floating-point numbers. These numeric values are classified under the number data type. The numeric data type is capable of representing both whole numbers and fractional values. Additionally, TypeScript accommodates Binary (Base 2), Octal (Base 8), Decimal (Base 10), and Hexadecimal (Base 16) literals.
Syntax:
let identifier: number = value;
Examples:-
let first: number = 12.0; // number
let second: number = 0x37CF; // hexadecimal
let third: number = 0o377 ; // octal
let fourth: number = 0b111001; // binary
console.log(first); // 123
console.log(second); // 14287
console.log(third); // 255
console.log(fourth); // 57
String
In TypeScript, the string data type will be utilized to represent text. The string type functions with textual information. We incorporate string literals into our scripts by surrounding them with single or double quotes. Additionally, it signifies a series of Unicode characters and allows for the embedding of expressions using the format $ {expr}.
Syntax
let identifier: string = " ";
Or
let identifier: string = ' ';
Examples
let empName: string = "Rohan";
let empDept: string = "IT";
// Before-ES6
let output1: string = employeeName + " works in the " + employeeDept + " department.";
// After-ES6
let output2: string = `${empName} works in the ${empDept} department.`;
console.log(output1);//Rohan works in the IT department.
console.log(output2);//Rohan works in the IT department.
Boolean
String and numeric data types can represent an infinite array of values, while the Boolean data type is restricted to just two possible values: "true" and "false." A Boolean value serves as a truth indicator that determines the veracity of a given condition.
Syntax
let identifier: Boolean = Boolean value;
Examples
let isDone: boolean = false;
A void serves as a return type for functions that do not yield any value. It is applicable in scenarios where no specific data type is present. A void type variable lacks utility since it can only be assigned the values undefined or null. The undefined data type signifies an uninitialized variable, while null indicates a variable that has no defined value.
Syntax
let unusable: void = undefined;
Examples
1. function helloUser(): void {
alert("This is a welcome message");
}
2. let tempNum: void = undefined;
tempNum = null;
tempNum = 123; //Error
Null signifies a variable with an undefined value. Similar to void, it is not particularly beneficial by itself. The Null type can only hold a single value, which is null. In TypeScript, the Null keyword is employed to declare the Null type; however, its utility is limited since it can only be assigned a null value.
Examples
let num: number = null;
let bool: boolean = null;
let str: string = null;
Undefined
The Undefined primitive type represents all variables that have not been initialized in TypeScript and JavaScript. It possesses a single value, which is undefined. In TypeScript, the undefined keyword signifies the undefined type; however, it lacks practical utility since it exclusively allows the assignment of an undefined value.
Example
let num: number = undefined;
let bool: boolean = undefined;
let str: string = undefined;
Any Type
In TypeScript, it serves as the "super type" for all data types. It is designed to represent any value that JavaScript can handle. This feature enables us to choose whether to engage in type-checking during the compilation process. When a variable cannot be categorized under any of the fundamental data types, it can be defined using the "Any" data type. The Any type is particularly beneficial when the type of a value is uncertain (such as when it originates from an API or a third-party library), allowing us to bypass type-checking during compile time.
Syntax
let identifier: any = value;
Examples
1. let val: any = 'Hi';
val = 555; // OK
val = true; // OK
2. function ProcessData(x: any, y: any) {
return x + y;
}
let result: any;
result = ProcessData("Hello ", "Any!"); //Hello Any!
result = ProcessData(2, 3); //5
User-Defined DataType
TypeScript accommodates the subsequent user-defined data types:
Array
An array represents a set of elements that share the same data type. Similar to JavaScript, TypeScript provides the capability to manipulate arrays of values. There are two methods to define an array:
- Utilize the element type followed by to indicate an array of that specific type:
- An alternative approach employs a generic array type:
var list : number[] = [1, 3, 5];
var list : Array<number> = [1, 3, 5];
Tuple
A Tuple is a data structure that consists of two collections of values, each potentially of different data types. It provides a means to represent a collection where the types of a specific number of elements are defined, yet they differ from one another. For instance, if we wish to denote a value as a combination of a numerical value and a string, it can be expressed as:
// Declare a tuple
let a: [string, number];
// Initialize it
a = ["hi", 8, "how", 5]; // OK
Interface
An Interface is a framework that serves as a contractual agreement within our application. It specifies the syntax that classes must adhere to, meaning any class that implements an interface is required to define all its members. While it cannot be directly instantiated, it can be referenced by the implementing class. The TypeScript compiler employs interfaces for type verification, a process commonly referred to as "duck typing" or "structural subtyping."
Example
interface Calc {
subtract (first: number, second: number): any;
}
let Calculator: Calc = {
subtract(first: number, second: number) {
return first - second;
}
}
Class
Classes serve the purpose of generating reusable components and function as a blueprint for object creation. They represent a conceptual entity that contains variables and methods to execute operations. TypeScript inherits its class functionality from ES6. This is distinct from an interface, which includes an implementation, while an interface itself lacks any inherent implementation.
Example
class Student
{
RollNo: number;
Name: string;
constructor(_RollNo: number, Name: string)
{
this.RollNo = _rollNo;
this.Name = _name;
}
showDetails()
{
console.log(this.rollNo + " : " + this.name);
}
}
Enums
Enums establish a collection of named constants. TypeScript offers enums that can be either string-based or numeric-based. By default, the enumeration of elements starts at 0; however, we have the option to modify this by explicitly assigning a value to one of the elements. The support for enums in TypeScript is derived from ES6.
Example
enum Color {
Red, Green, Blue
};
let c: Color;
Color = Color.Green;
Functions
A function serves as a logical unit of code that structures the program. Similar to JavaScript, TypeScript allows for the creation of functions in both named and anonymous forms. Functions contribute to the readability, maintainability, and reusability of our programs. A function declaration includes the name of the function, its return type, and its parameters.
Example
//named function with number as parameters type and return type
function add(a: number, b: number): number {
return a + b;
}
//anonymous function with number as parameters type and return type
let sum = function (a: number, y: number): number {
return a + b;
};
2. Generic
Generics are employed to develop components capable of operating with multiple data types instead of being limited to just one. This approach facilitates the creation of reusable components. It guarantees that the application remains adaptable and scalable over time. In TypeScript, generics utilize the type variable <T>, which signifies types. The structure of generic functions resembles that of non-generic functions, with the type parameters specified at the beginning, akin to function declarations.
Example
function identity<T>(arg: T): T {
return arg;
}
let output1 = identity<string>("myString");
let output2 = identity<number>( 100 );
3. Decorators
A decorator is a unique data type that can be applied to a class declaration, method, property, accessor, or parameter. It serves as a mechanism for incorporating annotations and a meta-programming syntax for both classes and functions. The usage of decorators is indicated by the "@" symbol.
A decorator represents an experimental capability that might evolve in upcoming versions. To activate decorator support, the experimentalDecorators compiler option needs to be set to true, either via the command line or within our tsconfig.json file.
Example
function f() {
console.log("f(): evaluated");
return function (target, propertyKey: string, descriptor: PropertyDescriptor) {
console.log("f(): called");
}
}
class C {
@f()
method() {}
}