Typescript Notes 2
Typescript Notes 2
Function in TypeScript:
Functions in TypeScript are similar to JavaScript functions but with the added benefit of static typing.
TypeScript allows you to specify the types of function parameters and return values, making your code more
robust and maintainable. Here are five examples of functions in TypeScript:
Functions in TypeScript allow you to specify and enforce type information for parameters and return values,
enhancing code quality and readability. You can use optional parameters, default values, rest parameters, and
function overloads to create flexible and type-safe functions.
Function type declarations in TypeScript allow you to define the shape and type of functions. These
declarations specify the types of parameters and return values for functions. Here are five examples of function
type declarations in TypeScript:
Function type declarations in TypeScript are a powerful tool for defining and enforcing the type of functions,
making your code more readable and providing static type checking. They allow you to specify the expected
input and output types of functions, which is especially helpful in larger codebases and collaborative
development.
Optional and default parameters in TypeScript allow you to define functions with flexibility by specifying
parameters that may not be required or have default values. Here are five examples that demonstrate optional
and default parameters in TypeScript:
Optional and default parameters in TypeScript make your functions more versatile and user-friendly by
allowing for flexibility in parameter usage. They are particularly useful when you want to provide a default
value for a parameter or make it optional without cluttering your function calls with undefined or null values.
Function overloads :
Function overloads in TypeScript allow you to define multiple function signatures for a single function. Each
signature specifies a different set of parameter types and return type. This helps TypeScript provide type-
checking based on the specific usage of the function. Here's a detailed explanation with examples:
function getItem(data: string[] | { [key: string]: string }, key: number | string): string {
if (Array.isArray(data)) {
return data[key as number];
} else {
return data[key as string];
}
}
Classes:
Classes in TypeScript are similar to classes in other object-oriented languages like Java and C#. They allow you
to define object blueprints with properties and methods, providing a clear structure for organizing and reusing
your code. Here are five examples to demonstrate classes in TypeScript:
typescript
Copy code
class Person {
firstName: string;
lastName: string;
getFullName(): string {
return `${this.firstName} ${this.lastName}`;
}
}
Example 2 - Inheritance:
class Animal {
name: string;
constructor(name: string) {
this.name = name;
}
makeSound(): string {
return "Some generic sound";
}
}
getEmployeeInfo(): string {
return `Employee ID: ${this.empId}, Name: ${this.fullName}`;
}
}
constructor(celsius: number) {
this.celsius = celsius;
}
}
const temperature = new Temperature(25);
console.log(temperature.celsius); // Accessing the getter
console.log(temperature.fahrenheit); // Accessing the getter for Fahrenheit
temperature.celsius = 30; // Accessing the setter
In this example, we use getter and setter methods to control access to temperature properties and provide
computed values.
Classes in TypeScript provide a structured way to model your code, allowing you to encapsulate data and
behavior. They also support inheritance, access modifiers, static members, and various other features, making
them a fundamental part of object-oriented programming in TypeScript.
constructors in TypeScript:
Constructors and properties in TypeScript are essential concepts when working with classes. Constructors are
special methods called when you create a new instance of a class, and properties are variables associated with
class instances. Let's dive into constructors and properties in TypeScript in detail:
Constructors:
Constructors are used to initialize the state of an object when it's created from a class.
In TypeScript, a constructor is a method named constructor within a class.
You can have only one constructor per class, and it's called when you use the new keyword to create an instance
of the class.
Constructors can accept parameters, allowing you to set initial values for class properties.
Example - Constructor with Parameters:
class Person {
firstName: string;
lastName: string;
Properties:
class Rectangle {
width: number;
height: number;
getArea(): number {
return this.width * this.height;
}
}
class BankAccount {
private balance: number;
constructor(initialBalance: number) {
this.balance = initialBalance;
}
TypeScript allows you to define getter and setter methods to control property access and modification.
Getters are used to retrieve the property value, and setters are used to change it.
They provide a way to perform additional logic when accessing or modifying properties.
Example - Getter and Setter:
class Temperature {
private _celsius: number;
constructor(celsius: number) {
this.celsius = celsius;
}
}
Constructors and properties in TypeScript play a crucial role in defining and initializing class instances. They
allow you to encapsulate data and logic within classes, making your code more organized and maintainable.
In TypeScript, inheritance allows you to create a new class that inherits properties and methods from an existing
class, referred to as the base or parent class. Abstract classes are a special type of class that cannot be
instantiated directly but can be used as a blueprint for other classes. Let's delve into inheritance and abstract
classes with examples:
Inheritance:
Inheritance in TypeScript involves creating a derived or child class that inherits members (properties and
methods) from a base or parent class. The derived class can also have additional members or override inherited
members. The primary keyword for inheritance is extends.
makeSound(): void {
console.log("Some generic sound");
}
}
class Vehicle {
protected speed: number;
constructor(speed: number) {
this.speed = speed;
}
Abstract Classes:
Abstract classes in TypeScript are designed to be used as base classes for other classes but cannot be
instantiated directly. They can contain abstract methods that must be implemented by derived classes. The
abstract keyword is used to define an abstract class or method.
typescript
Copy code
abstract class Shape {
abstract calculateArea(): number;
}
constructor(radius: number) {
super();
this.radius = radius;
}
calculateArea(): number {
return Math.PI * this.radius ** 2;
}
}
getSalary(): number {
// Implement the logic to calculate manager's salary
return 60000;
}
}
Summary:
Inheritance and abstract classes are fundamental concepts in object-oriented programming with TypeScript.
Inheritance allows you to create class hierarchies and share common properties and methods, while abstract
classes provide a blueprint for derived classes and ensure that certain methods or properties are implemented.
These features help you structure your code in a more organized and maintainable way.
Acess Modifiers:
Access modifiers in TypeScript provide control over the visibility and accessibility of class members
(properties and methods) within the class and from external code. TypeScript supports three main access
modifiers:
public: The default access modifier. Members marked as public are accessible from anywhere, both within the
class and externally.
private: Members marked as private are only accessible within the defining class. They cannot be accessed or
modified from outside the class.
protected: Members marked as protected are accessible within the defining class and its subclasses (derived
classes). They cannot be accessed from external code.
class Car {
public brand: string;
constructor(brand: string) {
this.brand = brand;
}
start(): void {
console.log(`Starting the ${this.brand} car.`);
}
}
constructor(initialBalance: number) {
this.balance = initialBalance;
}
constructor(age: number) {
this.age = age;
}
}
getAge(): number {
return this.age; // Accessing protected property in a subclass
}
}