HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / TypeScript / TypeScript Types

TypeScript Types

TypeScript supports type checking for basic types (primitives and object types). It 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 javascript programs are typescript programs as well.

Table of Contents

Static types
	- Primitive Types
	- Object Types
Generics
Decorators

1) Static types

In the context of language semantics and type systems, static types usually means “at compile time” or “without running a program”, while dynamic means “at runtime”. In a statically typed language, 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 i.e. number, string, boolean, void, 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 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
			
Touple Touple is just like array; but store values of different datatypes. It is also index based data structure just like 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 as 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) Generics

Generics allows to create a component that can work over a variety of types rather than a single one. e.g.

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 general sense, decorators are annotations. They are used with '@' symbol. It allows us to decorate classes and functions, similar to annotations in java and decorators in python.

Decorators is 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 it.

How to use 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. Drop me your questions in comments section.

Happy Learning !!

Was this post helpful?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

TypeScript Tutorial

  • TypeScript – Introduction
  • TypeScript – Types
  • TypeScript – Union Types
  • TypeScript – String Literal Types
  • TypeScript – var, let and const
  • TypeScript – Template Strings
  • TypeScript – Arithmetic Operators
  • TypeScript – Logical Operators
  • TypeScript – Comparison Operators
  • TypeScript – ‘for…of’ Loop
  • TypeScript – Spread Operator
  • TypeScript – Arrays
  • TypeScript – Enums
  • TypeScript – Map
  • TypeScript – Set
  • TypeScript – Functions
  • TypeScript – Function Overloading
  • TypeScript – Transpiler
  • TypeScript – Truthy and falsy
  • TypeScript – == vs ===
  • TypeScript – undefined vs null
  • TypeScript – Variable Hoisting
  • TypeScript – tsconfig.json

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces