[Go to site: main page, start]

0% found this document useful (0 votes)
5 views50 pages

TypeScript Notes

TypeScript is a superset of JavaScript developed by Microsoft that adds features like static typing and interfaces to improve code quality and maintainability. It compiles to plain JavaScript, ensuring compatibility with existing JavaScript environments and has gained widespread adoption in frameworks like Angular and Node.js. The documentation covers TypeScript's history, features, and key concepts such as type annotations, type inference, data types, and the TypeScript Compiler (tsc).

Uploaded by

bovile5038
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views50 pages

TypeScript Notes

TypeScript is a superset of JavaScript developed by Microsoft that adds features like static typing and interfaces to improve code quality and maintainability. It compiles to plain JavaScript, ensuring compatibility with existing JavaScript environments and has gained widespread adoption in frameworks like Angular and Node.js. The documentation covers TypeScript's history, features, and key concepts such as type annotations, type inference, data types, and the TypeScript Compiler (tsc).

Uploaded by

bovile5038
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

TypeScript Technical Documentation

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

Why Not Only JavaScript?


JavaScript:

1. Errors appear only at runtime


2. Difficult to refactor large projects
3. No type safety
4. Hard to maintain complex automation frameworks

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.

o TypeScript adds static typing on top of JavaScript, allowing errors to be detected at


compile time instead of runtime. This helped teams reduce bugs in complex projects.

1
TypeScript Technical Documentation

o TypeScript compiles (transpiles) to plain JavaScript, ensuring compatibility with all


browsers and JavaScript runtimes. This made adoption easy without changing existing
JavaScript workflows.

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

TypeScript 2.x – Better type checking, optional parameters

TypeScript 3.x – Improved performance and advanced types

TypeScript 4.x – Faster compilation, powerful type features

TypeScript 5.x (Latest) – Better performance, modern JavaScript support

What is a Transpiler?

• A transpiler converts code from one programming language to another.

• Mostly used to convert modern code into older, supported code.

• TypeScript is transpiled into JavaScript.

• Browser cannot understand TypeScript directly.

• After transpiling, JavaScript is executed by browser or [Link].

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

Why do we need tsc?


Browsers and [Link] cannot execute TypeScript directly.
tsc ensures that TypeScript code is validated, type-checked, and converted into standard
JavaScript that can run in any environment.

Main Responsibilities of tsc

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

npm install -g typescript // Global installation

tsc --version // Check version

tsc [Link] // Compile a single file

tsc --watch // Watch mode (auto recompile on changes)

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:

variableName: type = value;

Why Type Annotation is Needed

• Prevents runtime errors

• Improves code readability

• Provides compile-time type safety

• Helps IDEs with auto-suggestions

• Makes code self-documenting

Example:

let username: string = "Playwright";

let age: number = 25;

let isActive: boolean = true;

function add(a: number, b: number): number {

return a + b;

4
TypeScript Technical Documentation

When to Use Type Annotation


Use explicit type annotation when:

• A variable is declared without an initial value

• Functions have complex return logic

• Writing reusable utilities or APIs

• Working in large automation frameworks

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.

Why Type Inference is Important

• Reduces the need for explicit type annotations

• Keeps code clean and readable

• Maintains strong type safety

• Helps catch errors at compile time

• Improves developer productivity

Syntax:
let variable = value;

Example:
let message = "Hello"; // inferred as string

let count = 10; // inferred as number

let isVisible = true; // inferred as boolean

5
TypeScript Technical Documentation

When Type Inference is Enough

• Variable is initialized immediately

• Function logic is simple

• Local or internal variables

• Short, readable code is preferred

Difference Between Type Annotation and Type Inference


Type Annotation Type Inference

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.

Preferred in large-scale and enterprise Preferred for quick development and


projects. readability.

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:

let value: dataType = data;

6
TypeScript Technical Documentation

Primitive Data Types

Store single, simple values

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:

let name: string = "John";

let age: number = 25;

let isActive: boolean = true;


let big: bigint = 9007199254740991n;

let id: symbol = Symbol("userId");

7
TypeScript Technical Documentation

Type Description Example

string Text values "Hello"

number Integers & decimals 10, 3.14

boolean True / False true

bigint Large integers 123n

symbol Unique identifiers Symbol("id")

Non-Primitive (Reference) Data Types


Store collections or complex structures

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

object Key-value pairs

array List of values

function Reusable logic

tuple Fixed-length array

class Blueprint of objects

8
TypeScript Technical Documentation

Object in TypeScript

What is an Object in TypeScript?


An object is a collection of key–value pairs, where:
• Keys are property names
• Values can be any data type (string, number, boolean, array, function, another object)
TypeScript adds type safety on top of JavaScript objects.

Object with Type Annotation

let student: {
name: string; Benefits:
age: number; • Strong type checking
passed: boolean; • Prevents invalid data
}={
name: "Rahul",
age: 20,
passed: true
};

Optional Properties (?)

An optional property is an object property that may or may not exist.


It is marked using a question mark ? after the property name.

Syntax

type User = {
name: string;
age?: number; // optional property
};

9
TypeScript Technical Documentation

Object Type using type Alias

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;
};

Using Object Type with Type Alias

type Student = {
name: string;
age: number;
};

let student1: Student = {


name: "Rahul",
age: 20
};

let student2: Student = {


name: "Priya",
age: 21
};

Object with Methods (Functions inside Object)

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;
};

let p1: Person = {


name: "John",
greet() {
[Link]("Hello, " + [Link]);
}
};

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;
};

let user: UserProfile = {


name: "Kiran",
address: {
city: "Bangalore",
pincode: 560001
}
};

11
TypeScript Technical Documentation

Object with Array of Objects

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;
};

let arrayName: ObjectType[] = [


{ property1: value, property2: value },
{ property1: value, property2: value }
];

Example:

type Student = {
name: string;
age: number;
};

let students: Student[] = [


{ name: "Rahul", age: 20 },
{ name: "Priya", age: 21 }
];

Object as Function Parameter

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;
};

function functionName(param: ObjectType): returnType {


// access param.property1, param.property2
}

Example

type User = {
username: string;
age: number;
};

function displayUser(user: User): void {


[Link]([Link], [Link]);
}

displayUser ({ username: "John", age: 22 });

Type Alias

What is a Type Alias?

A type alias is a way to give a custom name to a type.


It helps make complex types readable, reusable, and maintainable.

Syntax

type AliasName = Type;

13
TypeScript Technical Documentation

Example

type UserName = string;


let name: UserName = "john";

Type Alias with Object

type Student = {
id: number;
name: string;
marks: number;
};

let s1: Student = {


id: 101,
name: "Anu",
marks: 85
};

Type Alias with Union

type Status = "success" | "error" | "loading";


let apiStatus: Status = "success"; //allowed
let apiStatus: Status = "error"; //allowed
let apiStatus: Status = "loading"; //allowed
let apiStatus: Status = "done"; // invalid

Type Alias with Function

type Add = (a: number, b: number) => number;


let sum: Add = (x, y) => x + y;

Type Alias with Array

type Scores = number[];


let marks: Scores = [90, 85, 88];

14
TypeScript Technical Documentation

Type Alias with Tuple

type UserTuple = [number, string];


let user: UserTuple = [1, "Admin"];

Type Alias with Intersection

type Person = {
name: string;
};

type Employee = {
empId: number;
};

type Staff = Person & Employee;

let staff1: Staff = {


name: "Ravi",
empId: 501
};

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

let numbers: number[];


// declares an array that can store only numbers

let names: string[] = ["A", "B"];


// declares and initializes a string array

let flags: Array<boolean>;


// declares a boolean array using generic syntax

15
TypeScript Technical Documentation

let scores: Array<number> = [80, 90];


// declares and initializes a number array using Array<Type>

let mixed: (number | string)[];


// declares an array that can store numbers or strings

let users: { id: number; name: string }[];


// declares an array of objects with id and name properties

type Student = { name: string; marks: number };


// defines a custom object type using type alias

let students: Student[];


// declares an array of Student type objects

let readonlyDays: readonly string[] = ["Mon", "Tue"];


// declares a readonly array that cannot be modified

let userTuple: [number, string];


// declares a tuple with fixed types and order

let matrix: number[][];


// declares a two-dimensional number array

function getValues(): number[] {


// function that returns a number array
return [1, 2, 3];
}

function printNames(values: string[]): void {


// function that accepts a string array as parameter
[Link](values);
}

let copyNumbers: number[] = [...numbers];


// creates a new array by spreading an existing array
let numbers: number[] = [10, 20, 30];

16
TypeScript Technical Documentation

Read & Write Array Elements

let colors: string[] = ["red", "green", "blue"];


colors[1] = "yellow";
[Link](colors[0]); // red

Array Length

let count: number = [Link];

Array of Objects

type Student = {
name: string;
marks: number;
};

let students: Student[] = [


{ name: "Anu", marks: 85 },
{ name: "Ravi", marks: 92 }
];

Tuple (Fixed Size Array)

let user: [number, string] = [1, "Admin"];

Readonly Array

let days: readonly string[] = ["Mon", "Tue"];


// [Link]("Wed"); //error

Union Type Array

let data: (number | string)[] = [1, "two", 3];

Spread Operator

let a: number[] = [1, 2];


let b: number[] = [...a, 3, 4];

17
TypeScript Technical Documentation

Tuple in TypeScript

What is a Tuple?

A tuple is a fixed-length array where:


• the order of elements matters
• each position has a specific type
Tuples are stricter than arrays

Syntax

let tupleName: [type1, type2];

Example

let user: [number, string] = [1, "Admin"];


//index 0 → number
//index 1 → string

Tuple with More Elements

let product: [number, string, number] = [101, "Mobile", 25000];

Tuple with Optional Element

let employee: [number, string, string?] = [1, "Ravi"];


//third value is optional

Tuple with Rest Elements

let scores: [string, ...number[]] = ["John", 80, 85, 90];


//first element fixed
//remaining are numbers

Tuple Read & Write

let data: [number, string] = [10, "TS"];


data[0] = 20; // allowed
data[1] = "JS"; // allowed

18
TypeScript Technical Documentation

Readonly Tuple

let point: readonly [number, number] = [10, 20];


// point[0] = 5 //Error

Tuple in Function Parameter

function printUser(user: [number, string]): void {


[Link](user[0], user[1]);
}

Tuple as Function Return Type

function getUser(): [number, string] {


return [1, "Admin"];
}

Tuple with Type Alias

type User = [number, string];


let u1: User = [2, "Guest"];

Union Types in TypeScript

What is a Union Type?

A union type allows a variable to hold one of multiple specified types.


Use | (pipe symbol)

Syntax

let value: type1 | type2;

Example

let id: number | string;


id = 101;
id = "A102"; // both are allowed

19
TypeScript Technical Documentation

Union with Function Parameter

function printId(id: number | string): void {


[Link](id);
}

Union Type Narrowing

Type narrowing allows TypeScript to determine the exact type of a variable from a union type
at runtime checks.

function display(value: string | number): void {


if (typeof value === "string") {
[Link]([Link]());
} else {
[Link]([Link](2));
}
}
//TypeScript understands the type inside the condition

Union with Array

let data: (number | string)[] = [1, "two", 3];

Union of Arrays

let values: number[] | string[];


//either all numbers OR all strings

Union with Object Types

type Student = {
name: string;
marks: number;
};
type Teacher = {
name: string;
subject: string;
};
let person: Student | Teacher;

20
TypeScript Technical Documentation

Discriminated (Tagged) Union

type Circle = {
shape: "circle";
radius: number;
};

type Rectangle = {
shape: "rectangle";
width: number;
height: number;
};

type Shape = Circle | Rectangle; //tagged union

function area(shape: Shape): number {


if ([Link] === "circle") {
return [Link] * [Link] * [Link];
}
return [Link] * [Link];
}
//safest and most powerful union usage

Union with Literal Types

let status: "success" | "error" | "loading";


status = "success"; // allowed

Union with Type Alias

type ID = number | string;


let userId: ID;

Intersection Types in TypeScript

What is an Intersection Type?

An intersection type combines multiple types into one.


The resulting type must satisfy all the combined types. Uses & (ampersand)

21
TypeScript Technical Documentation

Syntax

type NewType = TypeA & TypeB;

Simple Example

type Person = {
name: string;
};

type Employee = {
empId: number;
};

type Staff = Person & Employee;

let staff1: Staff = {


name: "Ravi",
empId: 101
};
//object must contain both properties

Intersection with Multiple Types

type A = { a: number };
type B = { b: string };
type C = { c: boolean };

type ABC = A & B & C;

Intersection with Function Types

type Log = (msg: string) => void;


type ErrorLog = (code: number) => void;

type Logger = Log & ErrorLog;


//function supports both signatures

22
TypeScript Technical Documentation

Intersection with Union Types

type Admin = { role: "admin" };


type User = { role: "user" };

type WithId = { id: number };

type Account = (Admin | User) & WithId;

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

A numeric enum stores number values.


If values are not assigned, it automatically starts from 0 and increments.

enum Direction {
Up,
Down,
Left,
Right
}
let move: Direction = [Link];
[Link](move); // 2
[Link](Direction[2]); // "Left" (reverse mapping)

23
TypeScript Technical Documentation

- Supports reverse mapping


- Auto-increment works

2. String Enum

A string enum stores string values.


Each member must be initialized with a string literal.

enum Role {
Admin = "ADMIN",
User = "USER"
}
let userRole: Role = [Link];
[Link](userRole); // "ADMIN"
[Link]([Link]); // "ADMIN"

- No reverse mapping
- More readable in APIs

3. Heterogeneous (Mixed) Enum

A mixed enum contains both numeric and string values.


Allowed but not recommended in real projects.

enum Result {
Pass = 1,
Fail = "FAIL"
}
let exam: Result = [Link];
[Link](exam); // 1
[Link]([Link]); // "FAIL"

- Avoid using mixed enums in production code.

4. Computed Enum

A computed enum contains values calculated using expressions.


After a computed value, automatic numbering is not allowed.

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

- Must manually assign values after computed members.

5. Const Enum

A const enum is removed during compilation for performance optimization.


No JavaScript object is created for it.

const enum Size {


Small,
Medium,
Large
}
let shirtSize = [Link];
[Link](shirtSize); // 1

- Reverse mapping not allowed


- Faster performance
- Cannot use reverse mapping

What is NOT Allowed in Enums

Duplicate Member Names

enum Test {
A = 1,
A = 2 // Error
}

25
TypeScript Technical Documentation

Auto increment after computed value

enum Sample {
A = [Link](),
B // Error
}

Modifying enum values

enum Status {
Active = 1
}
[Link] = 2; // Error

Reverse mapping in String Enum

enum Color {
Red = "RED"
}
[Link](Color["RED"]); // Error

Quick Comparison

Type Reverse Mapping Auto Increment Recommended Usage


Numeric Yes, supported Yes, supported Recommended
String No, not supported No, not supported Highly recommended
Mixed Partially supported Partially supported Not recommended
Computed Depends on definition Not supported Use with caution
Const No, not supported Yes, supported Recommended for performance

26
TypeScript Technical Documentation

Special Type

What is a Special Type in TypeScript?

A Special Type in TypeScript is a built-in type that is designed to handle special


situations in type checking — such as unknown values, functions that do not return,
or disabling type safety.
These types do not describe normal data like string or number.
Instead, they control how TypeScript behaves during type checking.

TypeScript Special Types

1. any

The any type allows a variable to hold any type of value. It disables type checking for that
variable.

let value: any = 10;


value = "Hello";
value = true;

Characteristics
• Can store values of any type
• TypeScript does not perform type checking
• All operations are allowed

let data: any = "TypeScript";


[Link]([Link]()); // No compile-time error

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.

let value: unknown = "Hello";

Characteristics
• Can store any value
• Cannot perform operations without type checking
• Requires type narrowing before usage

Example

let data: unknown = "TypeScript";


if (typeof data === "string") {
[Link]([Link]());
}

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.

function printLength(input: unknown) {


if (typeof input === "string") {
[Link]([Link]);
}
}

Difference Between any and unknown

Feature any unknown


Accepts any value Yes Yes
Type checking required No Yes
Safe for large projects No Yes

28
TypeScript Technical Documentation

3. void

The void type is used when a function does not return any value.

function greet(): void {


[Link]("Hello");
}

Characteristics
• Mainly used as a function return type
• Indicates that nothing is returned

Example

function logMessage(message: string): void {


[Link](message);
}

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.

Situations Where never Is Used


• Function throws an error
• Infinite loop
• Exhaustive type checking

Example 1: Function That Throws Error

function throwError(): never {


throw new Error("Something went wrong");
}

29
TypeScript Technical Documentation

Example 2: Infinite Loop

function infiniteLoop(): never {


while (true) {}
}

Example 3: Exhaustive Check

type Shape = "circle" | "square";


function getArea(shape: Shape) {
switch (shape) {
case "circle":
return 10;
case "square":
return 20;
default:
const check: never = shape;
}
}

Purpose
• Ensures all possible cases are handled
• Helps detect logical errors during development

Summary Table

Type Purpose Common Usage


any Disables type checking Temporary or dynamic values
unknown Safe unknown type External input, APIs
void No return value Functions
never Never returns Errors, infinite loops

30
TypeScript Technical Documentation

Type Assertion in TypeScript

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.

Why Do We Need Type Assertion?

Sometimes TypeScript cannot correctly infer the type.


In such cases, we manually specify the type.

Syntax

1. Angle Bracket Syntax

let value: unknown = "Hello";


let strLength: number = (<string>value).length;

2. as Syntax (Recommended)

let value: unknown = "Hello";


let strLength: number = (value as string).length;

The as syntax is preferred, especially in React projects.

Example: DOM Access

let input = [Link]("username") as HTMLInputElement;


[Link] = "Vishnu";
//Here we assert that the element is an HTMLInputElement.

Important Notes

• Type assertion does not perform runtime checking.


• It does not convert the type.
• It only affects compile-time behavior.

Type Assertion vs Type Casting

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 in TypeScript

Literal Types are types that represent exact values instead of general types.

Types of Literal Types

1. String Literal Types

let status: "success" | "error" | "loading";


status = "success"; // allowed

Used commonly in APIs and UI states.

2. Number Literal Types

let rating: 1 | 2 | 3 | 4 | 5;
rating = 5; // allowed

3. Boolean Literal Types

let isEnabled: true;


isEnabled = true; // only true allowed

Example

type Role = "admin" | "user" | "guest";


function login(role: Role) {
[Link]("Logged in as", role);
}

This ensures only predefined values are allowed.

Why Use Literal Types?

• Prevent invalid values


• Improve type safety
• Make APIs strict and predictable
• Useful with union types

32
TypeScript Technical Documentation

Difference Between Type Assertion and Literal Types

Feature Type Assertion Literal Types


Purpose Tell compiler about type Restrict variable to exact value
Runtime effect No No
Used for Type overriding Value restriction

Interface in TypeScript

Introduction to Interface

An Interface in TypeScript is a blueprint used to define the structure of an object.


It specifies:
• Property names
• Property types
• Method signatures
It does not contain implementation.
It only defines the shape of data.

Syntax

interface User {
name: string;
age: number;
}

let user1: User = {


name: "Vishnu",
age: 25
};

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;
}

let s1: Student = {


name: "Priya"
};
//grade is optional.

Readonly Properties

Used to prevent modification after initialization.

interface Product {
readonly id: number;
name: string;
}

let item: Product = {


id: 101,
name: "Laptop"
};

[Link] = "Mobile"; // allowed


// [Link] = 102; // not allowed

Method Definitions in Interface

Interfaces can define method signatures.

interface Person {
name: string;
greet(): void;
}

34
TypeScript Technical Documentation

let p1: Person = {


name: "Vishnu",
greet() {
[Link]("Hello");
}
};

Interface with Function Type

interface Add {
(a: number, b: number): number;
}

let sum: Add = (x, y) => x + y;

Here, the interface describes a function structure.

Interface with Array Type

interface StringArray {
[index: number]: string;
}

let arr: StringArray = ["a", "b", "c"];

This is called an index signature.

Extending Interfaces

Interfaces can extend other interfaces.

interface Animal {
name: string;
}

interface Dog extends Animal {


breed: string;
}

35
TypeScript Technical Documentation

let d1: Dog = {


name: "Tommy",
breed: "Labrador"
};

Multiple inheritance is also possible:

interface A {
a: string;
}

interface B {
b: number;
}

interface C extends A, B {
c: boolean;
}

Interface with Classes

A class can implement an interface.

interface Employee {
name: string;
getSalary(): number;
}

class Manager implements Employee {


name: string;

constructor(name: string) {
[Link] = name;
}

getSalary(): number {
return 50000;
}
} //The class must implement all interface members.

36
TypeScript Technical Documentation

Interface Declaration Merging

Interfaces with the same name automatically merge.

interface User {
name: string;
}

interface User {
age: number;
}

let u1: User = {


name: "Vishnu",
age: 25
};

Both declarations combine into one.

Difference Between Interface and Type Alias

Feature Interface Type Alias


Object structure Yes Yes
Extends Yes Yes
Declaration merging Yes No
Used for primitives No Yes
Used for unions No Yes

When to Use Interface

• When defining object structures


• When working with classes
• When designing APIs
• When expecting declaration merging

37
TypeScript Technical Documentation

Classes in TypeScript

Class

A class is a blueprint used to create objects with properties and methods.


It helps implement object-oriented programming concepts in TypeScript.

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

A constructor is a special method used to initialize class properties.


It runs automatically when an object is created.

Syntax

constructor(parameters) {
// initialization
}

Example

class Car {
brand: string;

constructor(brand: string) {
[Link] = brand;
}
}

Access - Can be public (default), private, or protected.

Pros
• Ensures proper initialization
• Allows parameter validation
Cons
• Too many parameters reduce readability
• Complex logic inside constructor is not recommended

Public

public makes properties and methods accessible from anywhere.


It is the default access modifier in TypeScript.

39
TypeScript Technical Documentation

Syntax

public property: type;

Example

class User {
public name: string = "Vishnu";
}

Access - Accessible inside class, subclasses, and outside the class.

Pros
• Easy access
• Simple to use
Cons
• Reduces data protection
• Can break encapsulation

private

private restricts access to within the same class only.


It protects sensitive data from external access.

Syntax

private property: type;

Example

class Account {
private balance: number = 1000;

getBalance(): number {
return [Link];
}
}

Access - Accessible only inside the class.

40
TypeScript Technical Documentation

Pros
• Strong encapsulation
• Protects data
Cons
• Cannot be accessed in subclasses
• Harder to test directly

protected

protected allows access within the class and its subclasses.


It prevents access from outside the class.

Syntax

protected property: type;

Example

class Animal {
protected sound: string = "Roar";
}

class Dog extends Animal {


makeSound() {
[Link]([Link]);
}
}

Access - Accessible inside class and subclasses only.

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

readonly property: type;

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

static members belong to the class rather than instances.


They can be accessed without creating an object.

Syntax

static property: type;


static method(): returnType {}

Example

class MathHelper {
static pi: number = 3.14;

static square(x: number): number {

42
TypeScript Technical Documentation

return x * x;
}
}

Access - Accessed using [Link], not through object.

Pros
• Memory efficient
• Good for utilities and constants
Cons
• Cannot access instance properties
• Reduces flexibility

Inheritance

Inheritance allows one class to extend another class.


It enables code reuse and hierarchical relationships.

Syntax

class Child extends Parent {}

Example

class Animal {
move(): void {
[Link]("Moving");
}
}

class Dog extends Animal {


bark(): void {
[Link]("Barking");
}
}

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

Method overriding allows a subclass to redefine a parent method.


It enables customized behavior in child classes.

Syntax

methodName(): returnType {
// new implementation
}

Example

class Animal {
speak(): void {
[Link]("Animal sound");
}
}

class Dog extends Animal {


speak(): void {
[Link]("Dog barks");
}
}

Access - Cannot reduce visibility of parent method.

Pros
• Supports polymorphism
• Flexible behavior
Cons
• Can cause confusion
• Needs proper documentation

44
TypeScript Technical Documentation

super

super is used to call the parent class constructor or methods.


It ensures proper initialization in inheritance.

Syntax

super(parameters);

Example

class Animal {
constructor(public name: string) {}
}

class Dog extends Animal {


constructor(name: string) {
super(name);
}
}

Access - Used inside subclass constructors or methods.

Pros
• Maintains inheritance chain
• Required for proper initialization
Cons
• Tight dependency on parent class
• Incorrect use may cause errors

Abstract Class

An abstract class cannot be instantiated directly.


It serves as a base class for other classes.

Syntax

abstract class ClassName {


abstract method(): returnType;
}

45
TypeScript Technical Documentation

Example

abstract class Shape {


abstract getArea(): number;
}

class Circle extends Shape {


constructor(public radius: number) {
super();
}

getArea(): number {
return [Link] * [Link] * [Link];
}
}

Access - Can have public, private, protected members.

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.

Why We Need Generics

Without generics, we either:


• Use a specific type (less reusable), or
• Use any (loses type safety).
Generics solve both problems by allowing dynamic types with safety.

46
TypeScript Technical Documentation

Generic Function

Syntax

function functionName<T>(parameter: T): T {


return parameter;
}

Example

function identity<T>(value: T): T {


return value;
}

let num = identity<number>(10);


let str = identity<string>("Hello");
// Here, T is a type parameter.

Generic with Multiple Types

Syntax

function functionName<T, U>(param1: T, param2: U): void {}

Example

function combine<T, U>(a: T, b: U): string {


return `${a} ${b}`;
}

combine<number, string>(10, "Apples");

Generic Interfaces

Syntax

interface InterfaceName<T> {
property: T;
}

47
TypeScript Technical Documentation

Example

interface Box<T> {
value: T;
}

let numberBox: Box<number> = { value: 100 };


let stringBox: Box<string> = { value: "Hello" };

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];
}
}

let store = new DataStore<string>("TypeScript");

Generic Constraints

Used to restrict the type that can be passed.

48
TypeScript Technical Documentation

Syntax

function functionName<T extends Type>(param: T) {}

Example

function printLength<T extends { length: number }>(item: T): number {


return [Link];
}

printLength("Hello");
printLength([1, 2, 3]);

Here, T must have a length property.

keyof with Generics

Used to restrict keys of an object.

Example

function getProperty<T, K extends keyof T>(obj: T, key: K) {


return obj[key];
}

const user = { name: "Vishnu", age: 25 };

getProperty(user, "name");

Default Generic Types

Syntax

class ClassName<T = DefaultType> {}

49
TypeScript Technical Documentation

Example

class Container<T = string> {


value: T;
constructor(value: T) {
[Link] = value;
}
}

let c1 = new Container("Hello");

Advantages of Generics

• Reusable code
• Strong type safety
• Avoids use of any
• Improves maintainability

Disadvantages of Generics

• Can be confusing for beginners


• Complex constraints reduce readability
• Overuse makes code harder to understand

**************************

50

You might also like