The TypeScript language supports different types of values. It provides data types for the JavaScript to transform it into a strongly typed programing language. JavaScript doesn't support data types, but with the help of TypeScript, we can use the data types feature in JavaScript. TypeScript plays an important role when the object-oriented programmer wants to use the type feature in any scripting language or object-oriented programming language. The Type System checks the validity of the given values before the program uses them. It ensures that the code behaves as expected.
TypeScript provides data types as an optional Type System. We can classify the TypeScript data type as following.
In the context of type systems, static types mean "at compile time" or "without running a program." In a statically typed language, variables, parameters, and objects have types that the compiler knows at compile time. The compiler used this information to perform the type checking.
Static types can be further divided into two sub-categories:
The TypeScript has five built-in data types, which are given below.
Like JavaScript, all the numbers in TypeScript are stored as floating-point values. These numeric values are treated like a number data type. The numeric data type can be used to represents both integers and fractions. TypeScript also supports Binary(Base 2), Octal(Base 8), Decimal(Base 10), and Hexadecimal(Base 16) literals.
let identifier: number = value;
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
We will use the string data type to represents the text in TypeScript. String type work with textual data. We include string literals in our scripts by enclosing them in single or double quotation marks. It also represents a sequence of Unicode characters. It embedded the expressions in the form of $ {expr}.
let identifier: string = " "; Or let identifier: string = ' ';
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.
The string and numeric data types can have an unlimited number of different values, whereas the Boolean data type can have only two values. They are "true" and "false." A Boolean value is a truth value which specifies whether the condition is true or not.
let identifier: Boolean = Boolean value;
let isDone: boolean = false;
A void is a return type of the functions which do not return any type of value. It is used where no data type is available. A variable of type void is not useful because we can only assign undefined or null to them. An undefined data type denotes uninitialized variable, whereas null represents a variable whose value is undefined.
let unusable: void = undefined;
1. function helloUser(): void { alert("This is a welcome message"); }
2. let tempNum: void = undefined; tempNum = null; tempNum = 123; //Error
Null represents a variable whose value is undefined. Much like the void, it is not extremely useful on its own. The Null accepts the only one value, which is null. The Null keyword is used to define the Null type in TypeScript, but it is not useful because we can only assign a null value to it.
let num: number = null; let bool: boolean = null; let str: string = null;
The Undefined primitive type denotes all uninitialized variables in TypeScript and JavaScript. It has only one value, which is undefined. The undefined keyword defines the undefined type in TypeScript, but it is not useful because we can only assign an undefined value to it.
let num: number = undefined; let bool: boolean = undefined; let str: string = undefined;
It is the "super type" of all data type in TypeScript. It is used to represents any JavaScript value. It allows us to opt-in and opt-out of type-checking during compilation. If a variable cannot be represented in any of the basic data types, then it can be declared using "Any" data type. Any type is useful when we do not know about the type of value (which might come from an API or 3rd party library), and we want to skip the type-checking on compile time.
let identifier: any = value;
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
TypeScript supports the following user-defined data types:
An array is a collection of elements of the same data type. Like JavaScript, TypeScript also allows us to work with arrays of values. An array can be written in two ways:
1. Use the type of the elements followed by [] to denote an array of that element type:
var list : number[] = [1, 3, 5];
2. The second way uses a generic array type:
var list : Array= [1, 3, 5];
The Tuple is a data type which includes two sets of values of different data types. It allows us to express an array where the type of a fixed number of elements is known, but they are not the same. For example, if we want to represent a value as a pair of a number and a string, then it can be written as:
// Declare a tuple let a: [string, number]; // Initialize it a = ["hi", 8, "how", 5]; // OK
An Interface is a structure which acts as a contract in our application. It defines the syntax for classes to follow, means a class which implements an interface is bound to implement all its members. It cannot be instantiated but can be referenced by the class which implements it. The TypeScript compiler uses interface for type-checking that is also known as "duck typing" or "structural subtyping."
interface Calc { subtract (first: number, second: number): any; } let Calculator: Calc = { subtract(first: number, second: number) { return first - second; } }
Classes are used to create reusable components and acts as a template for creating objects. It is a logical entity which store variables and functions to perform operations. TypeScript gets support for classes from ES6. It is different from the interface which has an implementation inside it, whereas an interface does not have any implementation inside it.
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 define a set of named constant. TypeScript provides both string-based and numeric-based enums. By default, enums begin numbering their elements starting from 0, but we can also change this by manually setting the value to one of its elements. TypeScript gets support for enums from ES6.
enum Color { Red, Green, Blue }; let c: Color; Color = Color.Green;
A function is the logical blocks of code to organize the program. Like JavaScript, TypeScript can also be used to create functions either as a named function or as an anonymous function. Functions ensure that our program is readable, maintainable, and reusable. A function declaration has a function's name, return type, and parameters.
//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; };
Generic is used to create a component which can work with a variety of data type rather than a single one. It allows a way to create reusable components. It ensures that the program is flexible as well as scalable in the long term. TypeScript uses generics with the type variable <T> that denotes types. The type of generic functions is just like non-generic functions, with the type parameters listed first, similarly to function declarations.
function identity<T>(arg: T): T { return arg; } let output1 = identity<string>("myString"); let output2 = identity<number>( 100 );
A decorator is a special of data type which can be attached to a class declaration, method, property, accessor, and parameter. It provides a way to add both annotations and a meta-programing syntax for classes and functions. It is used with "@" symbol.
A decorator is an experimental feature which may change in future releases. To enable support for the decorator, we must enable the experimentalDecorators compiler option either on the command line or in our tsconfig.json.
function f() { console.log("f(): evaluated"); return function (target, propertyKey: string, descriptor: PropertyDescriptor) { console.log("f(): called"); } } class C { @f() method() {} }