TypeScript Type System

TypeScript supports type checking for all primitive types and object types. TypeScript also supports generics, decorators, and ES6 module types as well.

It is important to learn that the type system in typescript is designed to be optional. So all programs written in JavaScript are TypeScript programs as well.

Table of Contents

1. Static types
    1.1. Primitive Types
    1.2. Object Types
2. Generics
3. Decorators

1. TypeScript Static Types

In the context of language semantics and type systems:

  • Static types usually mean “at compile time” or “without running a program”
  • Dynamic types mean “at runtime”

In a statically typed language (e.g. TypeScript), variables, parameters, and members of objects have types that the compiler knows at compile time. The compiler can use that information to perform type checks and to optimize the compiled code.

Static types in TypeScript can be divided into two sub-categories:

1.1. Primitive Types

TypeScript has 5 primary primitive types –

  1. number
  2. string
  3. boolean
  4. void
  5. any
Primitive TypeDescription
number Use to define variable of type number.

				let num: number = 123;
				num = 123.456;
				num = '123'; 	// Error
			
string Use to define variable of type string.

				let str: string = 'hello';
				str = 'world';
				str = 123; 	// Error
			
boolean Use to define variable of type boolean.

				let bool: boolean = false;
				bool = true;
				bool = 123; 	// Error
			
void
  1. Used on function return types to represent non-returning functions.
    			function warnUser(): void {
    			    alert("This is my warning message");
    			}
    			
  2. Declaring variables of type void is not useful because you can only assign undefined or null to them.
    			let tempVar: void = undefined;
    			tempVar = null;		
    
    			tempVar = 123;		//Error
    			
any Use any when you want to opt-out of type-checking and let the values pass through compile-time checks.

				let val: any = 'hello';
				
				val = 123; 		// OK

				val = true; 	// OK
			

1.2. Object Types

TypeScript supports the following object types.

Object TypeDescription
Array An array is a collection of values of the same datatype.

			var names:string[];	//declaration 

			names = ["how","to","do","in","java"];	//initialization
			
Tuple Tuple is just like array; but store values of different data types. It is also the index-based data structure just like an array.

			var items;	//declaration 

			items = ["how", 2, "do", 1 , true];	//initialization
			
Interface Interfaces define properties, methods, and events which deriving member classes must implement.

			interface ICalc { 
				add (first: number, second: number): any;
			} 

			let Calculator: ICalc = {
				add(first: number, second: number) {
					return first + second;
				}
			}
			
Class A class is a template for creating objects. Typescript gets support for classes from ES6.

			class Person { 

			   //field 
			   name:string; 
			 
			   //constructor 
			   constructor(name:string) { 
			      this.name = name; 
			   }  

			   //function 
			   speakName():void { 
			      console.log("Name is  :   "+this.name) 
			   } 
			}
			
Enum Like other programming languages, an Enum is a datatype consisting of a set of named values. The names are usually identifiers that behave like constants. Enums were introduced in ES6.

			enum Direction {
			    Up,
			    Down,
			    Left,
			    Right
			}

			let go: Direction;
			go = Direction.Up;
			
Function In TypeScript, we can declare variables who will point to only functions in their lifetime.

				let fun: Function = () => console.log("Hello");

				fun = 123; //Error
			

2. Generic Types

Generics allows creating a component that can work over a variety of types rather than only a single type.

function throwBack<T>(arg: T): T {	//Function return the parameter as it is
    return arg;
}

let outputStr = identity<string>("myString"); 	//OK

let outputNum = identity<number>( 100 ); 		//OK

3. Decorators

In a general sense, decorators are annotations. They are used with '@' symbol. Decorators allows us to decorate classes and functions, similar to annotations in Java and decorators in Python.

Decorators are a new feature that will probably make it into the ES7 version of JavaScript. However the functionality is available in TypeScript (experimental), so we can already make use of it.

3.1. How to use a Decorator

It is important to learn that every decorator is javascript function. To create decorator, create function like this:

function printable ( target ) {
	Object.defineProperty(target.prototype, 'print', {value: () => "Lokesh Gupta"});
}

@printable
class Person {
    
}

let admin = new Person();
console.log(admin.print()); // Lokesh Gupta

That’s all for type system in typescript.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.