Types: Learn about different types like numbers, strings, booleans, arrays, tuples, and enums, and how to use them.
Functions: Understand how to define functions with specific parameters and return types.
Classes: Explore how to create and use classes, including access modifiers, inheritance, abstract classes, and static members.
Interfaces: Discover how interfaces define the structure of objects and ensure they have specific properties and methods.
Generics: See how generics allow you to write flexible, reusable code that works with any data type
Types are used to define variables and function parameters
- Variables Number: Represents numeric values. let temperature: number = 22.5; String: Represents text values. let greeting: string = “Hello, world!”; Boolean: Represents true or false values. Array: Represents a collection of values. let colors: string[] = [“red”, “green”, “blue”]; Tuple: Represents an array with a fixed number of elements of specific types. let coordinates: [number, number] = [40.7128, -74.0060]; Enum: Represents a set of named constants. Any: Represents any type, bypassing type checking. Void: Represents the absence of a type, often used for functions that do not return a value. Null and Undefined: Represent null and undefined values. Object: Represents any non-primitive type. Never: Represents a value that never occurs (e.g., a function that always throws an error). Enums enum Color { Red, Green, Blue }
let favoriteColor: Color;
favoriteColor = Color.Green;
let anotherColor: Color = Color.Red;
Any
let randomValue: any;
randomValue = 10;
randomValue = "hello";
randomValue = true;
let anotherRandomValue: any = { key: "value" };
Null or Undefined
let nullableValue: string | null;
nullableValue = null;
let maybeUndefined: number | undefined;
maybeUndefined = undefined;
Object
let person: { name: string; age: number };
person = { name: "Alice", age: 25 };
let car: { make: string; model: string; year: number } = {
make: "Toyota",
model: "Corolla",
year: 2020
};
Never
function error(message: string): never {
throw new Error(message);
}
function infiniteLoop(): never {
while (true) {
}
}
- Functions Function with parameters and return type function add(a: number, b: number): number { return a + b; } Function with void return type function logMessage(message: string): void { console.log(message); } What is a Tuple A tuple in TypeScript is a special type of array where the type of elements is known and fixed.
let person: [string, number];
person = ["Alice", 25]; // Correct
person = [25, "Alice"]; // Wrong
In the function
// Function that returns a tuple
function getPersonInfo(): [string, number] {
return ["Alice", 25];
}
// Function that takes a tuple as a parameter
function printPersonInfo(person: [string, number]): void {
console.log(Name: ${person[0]}, Age: ${person[1]}
);
}
// Usage
const personInfo = getPersonInfo(); // personInfo is ["Alice", 25]
printPersonInfo(personInfo); // Logs: Name: Alice, Age: 25
Modify Tuple
let person: [string, number, number] = ["Alice", 25, 60];
// Modifying elements
person[0] = "Bob";
person[1] = 30;
person[2] = 70;
Classes
class Person {
// Fields
name: string;
age: number;
// Constructor
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
// Method
greet(): string {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}
// Usage
let person1 = new Person("Alice", 30);
console.log(person1.greet()); // Outputs: Hello, my name is Alice and I am 30 years old.
-
Access Modifiers
class Person {
// Public field
public name: string;// Private field
private age: number;// Protected field
protected isStudent: boolean;constructor(name: string, age: number, isStudent: boolean) {
this.name = name;
this.age = age;
this.isStudent = isStudent;
}// Public method
public greet(): string {
returnHello, my name is ${this.name}.
;
}// Private method
private getAge(): number {
return this.age;
}// Protected method
protected getStatus(): string {
return this.isStudent ? "I am a student." : "I am not a student.";
}
}
// Usage
let person = new Person("Alice", 30, true);
console.log(person.greet()); // Outputs: Hello, my name is Alice.
// console.log(person.getAge()); // Error: Property 'getAge' is private and only accessible within class 'Person'.
-
Inheritance
class Person {
name: string;constructor(name: string) {
this.name = name;
}greet(): string {
returnHello, my name is ${this.name}.
;
}
}
class Student extends Person {
studentId: number;
constructor(name: string, studentId: number) {
super(name); // Call the constructor of the base class
this.studentId = studentId;
}
displayId(): string {
return `My student ID is ${this.studentId}.`;
}
}
// Usage
let student = new Student("Bob", 12345);
console.log(student.greet()); // Outputs: Hello, my name is Bob.
console.log(student.displayId()); // Outputs: My student ID is 12345.
Interfaces
Interfaces in TypeScript are used to define the structure of an object. They specify what properties and methods an object should have, along with their types.
// Person.ts
export interface Person {
name: string;
age: number;
isStudent?: boolean; // Optional property
greet(): string;
}
// main.ts
import { Person } from './Person';
let person: Person = {
name: "Alice",
age: 25,
greet: function(): string {
return Hello, my name is ${this.name}
;
}
};
// Usage
console.log(person.greet()); // Outputs: Hello, my name is Alice
Did you notice{ } in the import statement?
The curly braces {} in the import statement are used to import named exports from a module.
If the module has multiple exports we use { }
// Person.ts
export interface Person {
name: string;
age: number;
isStudent?: boolean; // Optional property
greet(): string;
}
export const defaultGreeting = "Hello, world!";
// main.ts
import { Person, defaultGreeting } from './Person';
If the module has one export we don't need to use { }
// Person.ts
export default interface Person {
name: string;
age: number;
isStudent?: boolean;
greet(): string;
}
// main.ts
import Person from './Person';
Classes
class Person {
// Fields
name: string;
age: number;
// Constructor
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
// Method
greet(): string {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}
// Usage
let person1 = new Person("Alice", 30);
console.log(person1.greet()); // Outputs: Hello, my name is Alice and I am 30 years old.
-
Access Modifiers
class Person {
// Public field
public name: string;// Private field
private age: number;// Protected field
protected isStudent: boolean;constructor(name: string, age: number, isStudent: boolean) {
this.name = name;
this.age = age;
this.isStudent = isStudent;
}// Public method
public greet(): string {
returnHello, my name is ${this.name}.
;
}// Private method
private getAge(): number {
return this.age;
}// Protected method
protected getStatus(): string {
return this.isStudent ? "I am a student." : "I am not a student.";
}
}
// Usage
let person = new Person("Alice", 30, true);
console.log(person.greet()); // Outputs: Hello, my name is Alice.
// console.log(person.getAge()); // Error: Property 'getAge' is private and only accessible within class 'Person'.
-
Inheritance
class Person {
name: string;constructor(name: string) {
this.name = name;
}greet(): string {
returnHello, my name is ${this.name}.
;
}
}
class Student extends Person {
studentId: number;
constructor(name: string, studentId: number) {
super(name); // Call the constructor of the base class
this.studentId = studentId;
}
displayId(): string {
return `My student ID is ${this.studentId}.`;
}
}
// Usage
let student = new Student("Bob", 12345);
console.log(student.greet()); // Outputs: Hello, my name is Bob.
console.log(student.displayId()); // Outputs: My student ID is 12345.
-
Abstract Classes
abstract class Animal {
abstract makeSound(): void;move(): void {
console.log("Moving...");
}
}
class Dog extends Animal {
makeSound(): void {
console.log("Woof! Woof!");
}
}
// Usage
let dog = new Dog();
dog.makeSound(); // Outputs: Woof! Woof!
dog.move(); // Outputs: Moving...
-
Static Members
class MathUtils {
static PI: number = 3.14;static circleArea(radius: number): number {
return this.PI * radius * radius;
}
}
// Usage
// Static members (fields and methods) belong to the class itself,
// not to instances of the class.
console.log(MathUtils.PI); // Outputs: 3.14
console.log(MathUtils.circleArea(5)); // Outputs: 78.5
-
Getters and Setters
class Person {
private _name: string;constructor(name: string) {
this._name = name;
}get name(): string {
return this._name;
}set name(newName: string) {
if (newName.length > 0) {
this._name = newName;
} else {
console.error("Name cannot be empty");
}
}
}
// Usage
let person = new Person("Alice");
console.log(person.name); // Outputs: Alice
person.name = "Bob";
console.log(person.name); // Outputs: Bob
person.name = ""; // Error: Name cannot be empty
Generics
Generics in TypeScript provide a way to create reusable components that can work with a variety of types rather than a single type.
- Generic Function function identity(arg: T): T { return arg; }
// Usage
let output1 = identity("Hello");
let output2 = identity(123);
console.log(output1); // Outputs: Hello
console.log(output2); // Outputs: 123
-
Generic Classes
class GenericNumber {
value: T;
constructor(value: T) {
this.value = value;
}add(x: T, y: T): T {
return x; // Simplified for example purposes
}
}
// Usage
let myNumber = new GenericNumber(100);
console.log(myNumber.value); // Outputs: 100
let myString = new GenericNumber("Hello");
console.log(myString.value); // Outputs: Hello
- Generic Interfaces interface Pair { first: T; second: U; }
// Usage
let pair: Pair = {
first: "Alice",
second: 30
};
console.log(pair.first); // Outputs: Alice
console.log(pair.second); // Outputs: 30
- Generic Constraints interface Lengthwise { length: number; }
function logLength(arg: T): void {
console.log(arg.length);
}
// Usage
logLength("Hello"); // Outputs: 5
logLength([1, 2, 3]); // Outputs: 3
// logLength(10); // Error: Argument of type 'number' is not assignable to parameter of type 'Lengthwise'.
Top comments (0)