Setting Up TypeScript Projects and Exploring Classes
Project Setup:
To set up a TypeScript project, follow these steps in the VSCode terminal:
tsc --init
: Creates atsconfig.json
file.npm init -y
: Creates apackage.json
file.mkdir src dist
: Createssrc
for TypeScript files anddist
for distribution files.
Update tsconfig.json
:
{
"outDir": "./dist",
// other configurations...
}
Run TypeScript in watch mode:
tsc -w
Classes in TypeScript:
Classes serve as blueprints for creating objects with properties and methods. The class
keyword is used, and the constructor
method initializes object properties.
Example 1:
class User {
email: string;
name: string;
constructor(email: string, name: string) {
this.email = email;
this.name = name;
}
}
const person = new User("abc@gmail.com", "abdul");
Access Modifiers:
private
: Limits visibility to within the class itself.public
: Allows access from any part of the code.protected
: Permits access within the class and its subclasses.
Getters and Setters:
Getters and setters provide control over the internal state of a class.
Example:
class Example {
private _value: number = 0;
get value(): number {
return this._value;
}
set value(newValue: number) {
this._value = newValue;
}
}
const instance = new Example();
console.log(instance.value); // Accessing the getter
instance.value = 42; // Accessing the setter
Protected Access Modifier:
The protected
access modifier allows access within the class and its inherited classes.
Why is Interface Important?
Interfaces in TypeScript are crucial because they:
Structure Definition: Define the expected structure of objects.
Type Checking: Enable static type checking for robust code.
Code Organization: Organize code by encapsulating related properties and methods.
Example:
interface Person {
name: string;
age: number;
greet(): void;
}
class Employee implements Person {
constructor(public name: string, public age: number) {}
greet(): void {
console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
}
}
const john: Person = new Employee("John", 30);
john.greet();
This example showcases the use of an interface (Person
) to define a contract for objects, providing type checking and enhancing code organization.
Stay tuned for more TypeScript insights and practical tips!