TypeScript Notes
TypeScript Notes
Introduction to TypeScript
TypeScript is a programming language developed by Microsoft in 2012. It is a superset of
JavaScript, meaning any valid JavaScript code is also valid TypeScript code. TypeScript adds
additional features such as static typing, interfaces, enums, and better tooling support.
Why TypeScript?
• Detects errors at compile time
• Improves code readability and maintainability
• Provides strong typing and IntelliSense
• Makes large projects easy to manage
• Helps testers write reliable automation scripts
TypeScript solves all these problems by adding compile-time checks and type safety.
History of TypeScript
o TypeScript was introduced in 2012 by Microsoft to address scalability and
maintainability issues in large JavaScript applications.
It was designed to make JavaScript suitable for enterprise-level development.
o Anders Hejlsberg led the development of TypeScript, bringing strong typing concepts
from languages like C# and Delphi.
His goal was to improve developer productivity and code reliability.
1
TypeScript Technical Documentation
o Over time, TypeScript became widely adopted in frameworks and tools such as
Angular, [Link], and Playwright.
Versions of TypeScript
TypeScript 1.x (2012) – First release, basic static typing
What is a Transpiler?
What is tsc?
tsc stands for TypeScript Compiler.
It is a command-line tool provided by TypeScript that converts TypeScript code (.ts files) into
JavaScript (.js files) and checks for type-related errors during compilation.
2
TypeScript Technical Documentation
1. Transpilation
Converts .ts files into .js files based on the target JavaScript version (ES5, ES6, etc.).
2. Type Checking
Detects type mismatches, missing properties, invalid function arguments, and unsafe
operations at compile time.
3. Configuration Handling
Reads rules from [Link] such as strict mode, target version, module system, and
output directory.
4. Error Reporting
Displays detailed compile-time errors with file name, line number, and description.
5. Build Management
Compiles single files or entire projects and supports watch mode for continuous
compilation.
Installing tsc
When you install TypeScript, tsc is installed automatically.
Installation
3
TypeScript Technical Documentation
Type Annotation
Type Annotation is the process of explicitly specifying the data type of a variable, function
parameter, return value, or object in TypeScript.
It tells the compiler what type of value is expected, helping catch errors at compile time.
Syntax:
Example:
return a + b;
4
TypeScript Technical Documentation
Type Inference
Type Inference is a feature in TypeScript where the compiler automatically determines the data
type of a variable, expression, or function return value based on the assigned value or context.
This allows developers to write less code while still maintaining type safety.
Syntax:
let variable = value;
Example:
let message = "Hello"; // inferred as string
5
TypeScript Technical Documentation
Data type is explicitly specified by the Data type is automatically determined by the
developer. TypeScript compiler.
Requires more code to define types. Requires less code and keeps syntax clean.
Improves clarity in public APIs and Best suited for simple and local variables.
complex logic.
Gives full control over the declared Relies on the compiler’s intelligence.
type.
Data Types
A data type specifies the kind of value a variable can store and the operations that can be
performed on it.
In TypeScript, data types ensure type safety, correct operations, and reduced runtime errors.
General Syntax:
6
TypeScript Technical Documentation
A primitive data type is a basic data type that stores a single value directly in memory and is
immutable (its value cannot be changed once created).
Example:
7
TypeScript Technical Documentation
Non-primitive (reference) data types are data types that can store collections of values or
complex objects, and variables hold a reference (memory address) to the data rather than
the actual value and mutable (can be changed).
Type Description
8
TypeScript Technical Documentation
Object in TypeScript
let student: {
name: string; Benefits:
age: number; • Strong type checking
passed: boolean; • Prevents invalid data
}={
name: "Rahul",
age: 20,
passed: true
};
Syntax
type User = {
name: string;
age?: number; // optional property
};
9
TypeScript Technical Documentation
We create a custom name for an object’s structure using the type keyword, and then reuse that
structure wherever needed.
Basic Syntax
type TypeName = {
property1: type;
property2: type;
};
type Student = {
name: string;
age: number;
};
An object with methods in TypeScript is an object that contains functions as its properties,
allowing it to perform actions using its own data. These methods can access the object’s
properties using this, making the object behave like a real-world entity with both data and
behavior.
10
TypeScript Technical Documentation
type Person = {
name: string;
greet: () => void;
};
Nested Objects
Nested objects are objects that contain other objects as their property values. They are used to
represent complex, structured data like user details with address, profile, or settings inside a
single object.
type Address = {
city: string;
pincode: number;
};
type UserProfile = {
name: string;
address: Address;
};
11
TypeScript Technical Documentation
An object with an array of objects is a structure where a property holds a list of multiple objects
of the same type. It is commonly used to store collections like products, users, or orders within
a single parent object.
Syntax
type ObjectType = {
property1: type;
property2: type;
};
Example:
type Student = {
name: string;
age: number;
};
Object as a function parameter means passing an object to a function where the object’s
structure is predefined using a type or interface. This ensures the function receives the correct
properties and maintains type safety while accessing object data.
12
TypeScript Technical Documentation
Syntax
type ObjectType = {
property1: type;
property2: type;
};
Example
type User = {
username: string;
age: number;
};
Type Alias
Syntax
13
TypeScript Technical Documentation
Example
type Student = {
id: number;
name: string;
marks: number;
};
14
TypeScript Technical Documentation
type Person = {
name: string;
};
type Employee = {
empId: number;
};
Array in TypeScript
What is an Array?
An array in TypeScript stores multiple values of the same type in a single variable with type
safety.
Syntax
15
TypeScript Technical Documentation
16
TypeScript Technical Documentation
Array Length
Array of Objects
type Student = {
name: string;
marks: number;
};
Readonly Array
Spread Operator
17
TypeScript Technical Documentation
Tuple in TypeScript
What is a Tuple?
Syntax
Example
18
TypeScript Technical Documentation
Readonly Tuple
Syntax
Example
19
TypeScript Technical Documentation
Type narrowing allows TypeScript to determine the exact type of a variable from a union type
at runtime checks.
Union of Arrays
type Student = {
name: string;
marks: number;
};
type Teacher = {
name: string;
subject: string;
};
let person: Student | Teacher;
20
TypeScript Technical Documentation
type Circle = {
shape: "circle";
radius: number;
};
type Rectangle = {
shape: "rectangle";
width: number;
height: number;
};
21
TypeScript Technical Documentation
Syntax
Simple Example
type Person = {
name: string;
};
type Employee = {
empId: number;
};
type A = { a: number };
type B = { b: string };
type C = { c: boolean };
22
TypeScript Technical Documentation
Enums in TypeScript
1. What is an Enum?
An enum (enumeration) is a special type in TypeScript used to define a set of named
constants. It makes code more readable and meaningful.
enum Status {
Pending,
Approved,
Rejected
}
Types of Enums
1. Numeric Enum
enum Direction {
Up,
Down,
Left,
Right
}
let move: Direction = [Link];
[Link](move); // 2
[Link](Direction[2]); // "Left" (reverse mapping)
23
TypeScript Technical Documentation
2. String Enum
enum Role {
Admin = "ADMIN",
User = "USER"
}
let userRole: Role = [Link];
[Link](userRole); // "ADMIN"
[Link]([Link]); // "ADMIN"
- No reverse mapping
- More readable in APIs
enum Result {
Pass = 1,
Fail = "FAIL"
}
let exam: Result = [Link];
[Link](exam); // 1
[Link]([Link]); // "FAIL"
4. Computed Enum
24
TypeScript Technical Documentation
enum Numbers {
A = 10,
B = A + 5,
C = [Link]()
}
let num: Numbers = Numbers.B;
[Link](num); // 15
[Link](Numbers.C); // Random number
5. Const Enum
enum Test {
A = 1,
A = 2 // Error
}
25
TypeScript Technical Documentation
enum Sample {
A = [Link](),
B // Error
}
enum Status {
Active = 1
}
[Link] = 2; // Error
enum Color {
Red = "RED"
}
[Link](Color["RED"]); // Error
Quick Comparison
26
TypeScript Technical Documentation
Special Type
1. any
The any type allows a variable to hold any type of value. It disables type checking for that
variable.
Characteristics
• Can store values of any type
• TypeScript does not perform type checking
• All operations are allowed
When to Use
• During migration from JavaScript to TypeScript
• When working with third-party libraries without type definitions
• When the type is completely dynamic
Important Note
Overusing any removes the main advantage of TypeScript, which is type safety.
27
TypeScript Technical Documentation
[Link]
The unknown type represents a value whose type is not known at the time of writing code. It is
a safer alternative to any.
Characteristics
• Can store any value
• Cannot perform operations without type checking
• Requires type narrowing before usage
Example
Type Narrowing
Type Narrowing is the process of reducing a variable’s broad or general type into a more
specific type based on certain checks performed in the code.
(OR)
Type narrowing means telling TypeScript exactly what type a variable is at a specific point in
the program.
28
TypeScript Technical Documentation
3. void
The void type is used when a function does not return any value.
Characteristics
• Mainly used as a function return type
• Indicates that nothing is returned
Example
Note
A function with void return type may return undefined, but it should not return any meaningful
value.
4. never
The never type represents values that never occur. It is used when a function never completes
normally.
29
TypeScript Technical Documentation
Purpose
• Ensures all possible cases are handled
• Helps detect logical errors during development
Summary Table
30
TypeScript Technical Documentation
Type Assertion is a feature in TypeScript that allows a developer to manually specify the type
of a value when the compiler cannot automatically infer it correctly.
Syntax
2. as Syntax (Recommended)
Important Notes
TypeScript type assertion is not real type conversion like in other languages.
It only tells the compiler to treat the value as a specific type.
31
TypeScript Technical Documentation
Literal Types are types that represent exact values instead of general types.
let rating: 1 | 2 | 3 | 4 | 5;
rating = 5; // allowed
Example
32
TypeScript Technical Documentation
Interface in TypeScript
Introduction to Interface
Syntax
interface User {
name: string;
age: number;
}
Here, the object must follow the structure defined in the interface.
33
TypeScript Technical Documentation
Optional Properties
We can make properties optional using ?.
interface Student {
name: string;
grade?: number;
}
Readonly Properties
interface Product {
readonly id: number;
name: string;
}
interface Person {
name: string;
greet(): void;
}
34
TypeScript Technical Documentation
interface Add {
(a: number, b: number): number;
}
interface StringArray {
[index: number]: string;
}
Extending Interfaces
interface Animal {
name: string;
}
35
TypeScript Technical Documentation
interface A {
a: string;
}
interface B {
b: number;
}
interface C extends A, B {
c: boolean;
}
interface Employee {
name: string;
getSalary(): number;
}
constructor(name: string) {
[Link] = name;
}
getSalary(): number {
return 50000;
}
} //The class must implement all interface members.
36
TypeScript Technical Documentation
interface User {
name: string;
}
interface User {
age: number;
}
37
TypeScript Technical Documentation
Classes in TypeScript
Class
Syntax
class ClassName {
property: type;
constructor(parameter: type) {
[Link] = parameter;
}
method(): returnType {}
}
Example
class Person {
name: string;
constructor(name: string) {
[Link] = name;
}
greet(): void {
[Link]("Hello " + [Link]);
}
}
Access - Can contain public, private, protected, readonly, and static members.
Pros
• Provides structure and reusability
• Supports OOP concepts
38
TypeScript Technical Documentation
Cons
• Can increase complexity
• Overuse may create deep inheritance chains
Constructor
Syntax
constructor(parameters) {
// initialization
}
Example
class Car {
brand: string;
constructor(brand: string) {
[Link] = brand;
}
}
Pros
• Ensures proper initialization
• Allows parameter validation
Cons
• Too many parameters reduce readability
• Complex logic inside constructor is not recommended
Public
39
TypeScript Technical Documentation
Syntax
Example
class User {
public name: string = "Vishnu";
}
Pros
• Easy access
• Simple to use
Cons
• Reduces data protection
• Can break encapsulation
private
Syntax
Example
class Account {
private balance: number = 1000;
getBalance(): number {
return [Link];
}
}
40
TypeScript Technical Documentation
Pros
• Strong encapsulation
• Protects data
Cons
• Cannot be accessed in subclasses
• Harder to test directly
protected
Syntax
Example
class Animal {
protected sound: string = "Roar";
}
Pros
• Supports inheritance
• Maintains controlled access
Cons
• Slightly complex
• May expose data to subclasses unnecessarily
readonly
readonly makes a property unchangeable after initialization.
It ensures immutability of class data.
41
TypeScript Technical Documentation
Syntax
Example
class Product {
readonly id: number;
constructor(id: number) {
[Link] = id;
}
}
Access - Can be public, private, or protected but value cannot change after assignment.
Pros
• Prevents accidental changes
• Improves reliability
Cons
• Not suitable for frequently changing values
• Requires new object creation for updates
static
Syntax
Example
class MathHelper {
static pi: number = 3.14;
42
TypeScript Technical Documentation
return x * x;
}
}
Pros
• Memory efficient
• Good for utilities and constants
Cons
• Cannot access instance properties
• Reduces flexibility
Inheritance
Syntax
Example
class Animal {
move(): void {
[Link]("Moving");
}
}
Access Rules
• public → everywhere
• protected → subclass allowed
• private → not inherited
43
TypeScript Technical Documentation
Pros
• Code reuse
• Logical structure
Cons
• Tight coupling
• Deep inheritance can be hard to manage
Method Overriding
Syntax
methodName(): returnType {
// new implementation
}
Example
class Animal {
speak(): void {
[Link]("Animal sound");
}
}
Pros
• Supports polymorphism
• Flexible behavior
Cons
• Can cause confusion
• Needs proper documentation
44
TypeScript Technical Documentation
super
Syntax
super(parameters);
Example
class Animal {
constructor(public name: string) {}
}
Pros
• Maintains inheritance chain
• Required for proper initialization
Cons
• Tight dependency on parent class
• Incorrect use may cause errors
Abstract Class
Syntax
45
TypeScript Technical Documentation
Example
getArea(): number {
return [Link] * [Link] * [Link];
}
}
Pros
• Enforces structure
• Supports partial implementation
Cons
• Cannot create direct objects
• Adds abstraction complexity
Generics in TypeScript
Introduction to Generics
Generics allow us to create reusable components that work with different data types.
They provide flexibility while maintaining strong type safety.
46
TypeScript Technical Documentation
Generic Function
Syntax
Example
Syntax
Example
Generic Interfaces
Syntax
interface InterfaceName<T> {
property: T;
}
47
TypeScript Technical Documentation
Example
interface Box<T> {
value: T;
}
Generic Classes
Syntax
class ClassName<T> {
property: T;
constructor(value: T) {
[Link] = value;
}
}
Example
class DataStore<T> {
data: T;
constructor(data: T) {
[Link] = data;
}
getData(): T {
return [Link];
}
}
Generic Constraints
48
TypeScript Technical Documentation
Syntax
Example
printLength("Hello");
printLength([1, 2, 3]);
Example
getProperty(user, "name");
Syntax
49
TypeScript Technical Documentation
Example
Advantages of Generics
• Reusable code
• Strong type safety
• Avoids use of any
• Improves maintainability
Disadvantages of Generics
**************************
50