TypeScript Tutorial
Written By: Avinash Malhotra
Updated on
TypeScript
TypeScript is a superset of JavaScript ES6 that adds static type checking and advanced object-oriented features. Developed and maintained by Microsoft, TypeScript is the preferred language for building scalable applications with Angular and other modern frameworks. TypeScript code is transpiled to JavaScript, enabling type safety during development while delivering standard JavaScript for browsers.
All valid JavaScript ES6 code is automatically valid TypeScript. You can optionally add type annotations like let x:number=3; alongside standard syntax like let x=3;. The TypeScript compiler transpiles both pure ES6 and TypeScript code to JavaScript, and can target earlier versions like ES5 for broader browser compatibility.
TypeScript Advantages
- Static type checking (any, string, number, etc.)
- Type annotations for function parameters and return values
- Automatic type inference reduces boilerplate code
- Interfaces for structured object contracts
- Generics for type-safe reusable components
- Early error detection catches bugs at compile time
- Enhanced IDE support and autocomplete
Prerequisites for Learning TypeScript
Many beginners ask, Can I learn TypeScript without JavaScript?
The answer is no. TypeScript is a JavaScript superset with additional features, meaning the syntax and runtime behavior remain consistent with JavaScript fundamentals.
- HTML5
- CSS3
- JavaScript ES6 and above ( Expertise level )
To learn JavaScript, visit our free JavaScript Tutorial.
Install TypeScript
TypeScript is available on npm. You can install the latest stable version or the next available beta version. Ensure you have Node JS installed first, since npm comes bundled with Node JS. Need help? Follow our Node JS installation guide.
Install TypeScript Stable
Install Stable version of typescript.
Install TypeScript Next
Install next version of typescript.
Verify TypeScript
Verify whether TypeScript is installed or not.
Version 4.9.3
Transpile
TypeScript files use the .ts extension, but browsers can only execute JavaScript (.js files). The TypeScript compiler transpiles .ts files to .js, which you can then link in web applications or execute in Node.js.
Compile TS
Compile TypeScript to ES6
Compile and Run TypeScript in Node
Types
TypeScript includes built-in support for types such as string, number, boolean, and more. Type annotations specify what kind of data a variable can hold, enabling the compiler to catch type mismatches before runtime.
Core TypeScript Types
- any - accept any data type
- string - text values
- number - integers and decimals
- boolean - true or false
- undefined - uninitialized value
- function - reusable code blocks
- array - collections of values
Default Type (Type Inference)
let x="hello world";
let y=22;
any type
let x:any="hello world";
let y=22;
String Type
let x:string="hello world";
Number Type
let x:number=3;
Parameter Type
function sayHi(name: string{ return `Hello ${name}.` }
return Type
function getArea(r: number):number{ return Math.PI * r * r; }
Types by Inference
TypeScript automatically infers types using its intelligent type system. Values in quotes are automatically treated as strings, while numeric values are treated as numbers, eliminating the need for explicit type declarations in many cases.
In JavaScript, we can change variable with string to another datatype like number, boolean etc.
let user="avinash"; // user is string
Unlike JavaScript, TypeScript enforces type safety. If a variable is inferred or declared as a string during initialization, it can only store string values. Attempting to assign a different datatype triggers a compilation error, preventing type-related bugs.
error TS2322: Type 'string' is not assignable to type 'number'.
let id=3; // id is number
id="hello"; // error
hello
let id:any=3; // id is number
id="hello"; // id is string now
Interface
Interfaces define the structure and types of object properties. In JavaScript, object properties can hold any datatype, but TypeScript interfaces enforce strict contracts by specifying which properties must exist and their exact types.
interface User{
name:string;
id:number;
}
const user:User={
name:"Avinash",
id:212,
};
Interface with classes
interface User{
name:string;
id:number;
}
class UserData{
name:string;
id:number;
constructor(name: string, id: number) {
this.name = name;
this.id = id;
}
}
const user: User = new UserData("Avinash", 212);
Generics
Generics allow you to create reusable, type-safe components. In JavaScript, arrays can mix any datatypes (strings and numbers together), which complicates operations like sorting. Generics enforce that arrays contain only a single datatype, preventing type-related errors and simplifying logic.
- StringArray
- NumberArray
- ObjectWithNameArray
StringArray Generic
A StringArray generic ensures that an array stores only string values, providing type safety and compile-time error detection.
type StringArray=Array<string>;
const month:StringArray=["jan","feb"];
NumberArray Generic
NumberArray ensures an array contains only numeric values, eliminating the need for type-checking during operations like sorting.
type NumberArray=Array<number>;
const data:NumberArray=[1,3,8,10];
ObjectWithNameArray Generic
ObjectWithNameArray restricts arrays to objects that have a specific name property, ensuring structural consistency across collections.
type ObjectWithNameArray=Array<{name:string}>;
const cars:ObjectWithNameArray = [
{name:"swift"},
{name:"alto"},
];
Classes
TypeScript fully supports ES6 classes, providing a clean, structured way to create objects and manage state. While JavaScript ES5 relied on function-based constructors, both modern JavaScript and TypeScript now support class syntax with additional features.
TypeScript enhances classes with access modifiers (public and private) for encapsulation, a capability not yet fully standardized in JavaScript.
If you are not familiar with Classes in JavaScript, just go through our JavaScript Class Tutorial first.
Declaring a Class in TypeScript
sum of 2 and 3 is 5
class Sum{
x:number=2;
y:number=3;
getSum(){ return `sum of ${this.x} and ${this.y} is ${this.x+this.y}`; }
}
// create instance
const sum=new Sum();
console.log( sum.getSum() );
Class with constructor
To pass x any y dynamically, we can use constructor function in class.
sum of 4 and 5 is 9
class Sum{
x:number;
y:number;
constructor(x:number=0,y:number=0){
this.x=x;
this.y=y;
}
getSum(){ return `sum of ${this.x} and ${this.y} is ${this.x+this.y}`; }
}
const sum=new Sum(4,5);
console.log( sum.getSum() );
Public and Private Access Modifiers
Access modifiers control visibility and mutability of class properties. By default, properties are public, meaning they can be accessed and modified from outside the class. TypeScript's public and private modifiers provide explicit control over property accessibility.
In the examples above, x and y are public by default, allowing external code to read and modify them.
Public
sum of 4 and 5 is 9
class Sum{
x:number; // public
y:number; // public
constructor(x:number=0,y:number=0){
}
getSum(){ return `sum of ${this.x} and ${this.y} is ${this.x+this.y}`; }
}
const sum=new Sum(4,5);
console.log( sum.getSum() );
Public in Constructor (Recommended Approach)
This pattern is the TypeScript best practice, combining property declaration and initialization in the constructor signature. It reduces boilerplate while maintaining clarity and is one of TypeScript's most powerful features.
sum of 4 and 5 is 9
class Sum{
constructor(public x:number=0, public y:number=0){ }
getSum(){ return `sum of ${this.x} and ${this.y} is ${this.x+this.y}`; }
}
const sum=new Sum(4,5);
console.log( sum.getSum() );
Private Fields
Private fields restrict access to properties only within the class. External code cannot read or modify private properties, enforcing encapsulation and protecting internal state from unwanted changes.
2
Property 'pi' is private and only accessible within class 'Area'
class Area{
private pi:number=3.14; // private
r:number=2; // public
}
const area=new Area();
console.log(area.r );
console.log(area.pi );
Written by Avinash Malhotra, IIT Alumni, 13+ Experience, Certified Corporate Trainer.