Skip to content

Commit

Permalink
Merge branch '06_02e' into 06_03
Browse files Browse the repository at this point in the history
  • Loading branch information
BrightBoost committed Jun 9, 2024
2 parents 55d6891 + 115c881 commit 4ab56b2
Show file tree
Hide file tree
Showing 32 changed files with 584 additions and 14 deletions.
10 changes: 10 additions & 0 deletions 1-working-with-generics/1-1-generics/ElementHolder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,13 @@ export class ElementHolder<T> implements Printer<T> {
this.values = this.values.filter(v => v !== value);
}
}


const holder = new ElementHolder<string>(["hello", "world", "typescript"]);
holder.printAll(); // This will print "hello", "world", "typescript"

holder.add("new element");
holder.printAll(); // Now prints "hello", "world", "typescript", "new element"

holder.remove("world");
holder.printAll(); // Now prints "hello", "typescript", "new element"
3 changes: 3 additions & 0 deletions 1-working-with-generics/1-1-generics/KeyValuePair.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,6 @@ class KeyValuePair<K, V> {
console.log(`Key: ${this.key} - Value: ${this.value}`);
}
}

let pair = new KeyValuePair<string, string>("url", "something.com");
pair.displayPair();
10 changes: 10 additions & 0 deletions 1-working-with-generics/1-1-generics/Response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,16 @@ export interface Response<T> {
data: T;
}

function createResponse<T>(status: number, message: string, data: T): Response<T> {
return { status, message, data };
}

const stringResponse = createResponse<string>(200, "OK", "This is a successful response");
console.log(stringResponse);

const numbersResponse = createResponse<number[]>(200, "OK", [1, 2, 3, 4]);
console.log(numbersResponse);




3 changes: 3 additions & 0 deletions 1-working-with-generics/1-1-generics/exampleWithGenerics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ function printSomething<Type>(arg: Type): Type {
return arg;
}

let someValue = printSomething<string>("something");
// let someValue2 = printSomething<string>(3);
let someValue3 = printSomething("some other thing");

function printSomething2<T, U, V>(arg1: T, arg2: U): V {
// some body that logically results in a value of type V
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
function printSomething3(arg: string): string {
console.log(arg);
return arg;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,22 @@ function logLength<T extends { length: number }>(item: T): void {
console.log(item.length);
}

logLength("Hello TypeScript");
logLength([2]);



function processSerializable<T extends { serialize: () => string }>(item: T) {
console.log(item.serialize());
}

class User {
constructor(public name: string, public age: number) {}

serialize(): string {
return JSON.stringify({name: this.name, age: this.age});
}
}

const user = new User("Dione", 35);
processSerializable(user);
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,7 @@ class SomeList<T = string> {
this.list.push(t)
}
}

const stringList = new SomeList();
stringList.add("TS");
stringList.add("is cool");
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,6 @@ const appConfig: AppConfig = {
logLevel: 'info',
port: 3000
};

const debugStatus = getConfigValue(appConfig, 'debug');
const appPort = getConfigValue(appConfig, 'port');
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { DocumentFactory } from "./DocumentFactory";
const factory = new DocumentFactory();

const wordDoc = factory.createDocument("word");
wordDoc.content = "Hello, the bird is the word";
wordDoc.printContent();

const excelDoc = factory.createDocument("excel");
excelDoc.content = "Data1, Data2, Data3";
excelDoc.printContent();

try {
const pdfDoc = factory.createDocument("pdf");
} catch(error) {
console.log(error);
}
4 changes: 3 additions & 1 deletion 2-advanced-types/2-1-utility-types/Todo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,7 @@ type TodoPreview = Pick<Todo, "title" | "completed">;

const todoPreview: TodoPreview = {
title: "Finish article",
completed: false,
completed: false
};


2 changes: 1 addition & 1 deletion 2-advanced-types/2-1-utility-types/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,4 @@ const user: Readonly<User> = {
};

// Error: Cannot assign to 'name' because it is a read-only property.
user.name = "Marya A";
// user.name = "Marya A";
2 changes: 1 addition & 1 deletion 2-advanced-types/2-1-utility-types/exampleRecord.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ const userStatus: Record<number, Status> = {
3: "pending",
};

console.log(userStatus[1]); // Output: "active" (video)
console.log(userStatus[1]); // Output: "active"
37 changes: 37 additions & 0 deletions 2-advanced-types/2-1-utility-types/otherExamples.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,41 @@
type AvailableDrinks = "Coffee" | "Tea" | "Water" | "Soda";
type NonCaffeinated = Exclude<AvailableDrinks, "Coffee" | "Tea">;

type SomeDrinks = Extract<AvailableDrinks, "Coffee" | "Tea" >;

type MaybeString = string | null | undefined;
type JustString = NonNullable<MaybeString>; // string

function getString() {
return "hello";
}

type MyString = ReturnType<typeof getString>; // string

class MyClass {
x: number;
y: number;

constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}

type ConstructorParams = ConstructorParameters<typeof MyClass>;

type MyInstance = InstanceType<typeof MyClass>; // MyClass

function greet(name: string, age: number) {
console.log(`Hello ${name}, you are ${age} years old.`);
}

type Params = Parameters<typeof greet>; // [string, number]

function fn(this: string, age: number) {
console.log(this.toUpperCase());
}

type ThisParamsType = ThisParameterType<typeof fn>; // string

const fnWithoutThis: OmitThisParameter<typeof fn> = fn.bind("Hello");
2 changes: 1 addition & 1 deletion 2-advanced-types/2-2-mapped-types/Person.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export interface Person {
export type Person = {
name: string;
age: number;
}
4 changes: 4 additions & 0 deletions 2-advanced-types/2-2-mapped-types/optionalPerson.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,7 @@ type OptionalPerson = {
[Property in keyof Person]?: Person[Property];
}

const person: OptionalPerson = {
name: "Maryam", // 'age' is now optional thanks to the mapped type
};

6 changes: 4 additions & 2 deletions 2-advanced-types/2-2-mapped-types/readOnlyPerson.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { Person } from './Person';

type ReadonlyPerson = {
[Property in keyof Person]: Readonly<Person[Property]>;
}
readonly [Property in keyof Person]: Person[Property];
};

const readPerson: ReadonlyPerson = {
name: "Adnane",
age: 38
};

// readPerson.name = "Another name"; // Read only, so not allowed
2 changes: 1 addition & 1 deletion 2-advanced-types/2-2-mapped-types/stringifiedPerson.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ type StringifiedPerson = {

const stringPerson: StringifiedPerson = {
name: "Pradeepa",
age: "30" // Note: 'age' is now a string
age: "30" // Note: 'age' is now a string
};
17 changes: 17 additions & 0 deletions 3-mastering-function-overloading/3-2-practical-use-case/log.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
function log(message: string): void;
function log(error: Error): void;
function log(message: string, error: Error): void;
function log(param1: string | Error, param2?: Error): void {
if (typeof param1 === 'string' && param2 instanceof Error) {
console.error(`Error: ${param1}`, param2);
} else if (param1 instanceof Error) {
console.error(param1);
} else {
console.log(param1);
}
}

// Usage
log("User login successful.");
log(new Error("Failed to connect to database."));
log("User request failed.", new Error("Session timeout"));
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
interface User {
id: number;
username: string;
email: string;
}

function getUser(id: number): User;
function getUser(username: string): User[];
function getUser(id: number, username: string): User;
function getUser(param1: number | string, param2?: string): User | User[] {
if (typeof param1 === 'number' && param2) {
// Fetch user by ID and username
console.log(`Fetching user by ID: ${param1} and username: ${param2}`);
return { id: param1, username: param2, email: "[email protected]" }; // Simulated data
} else if (typeof param1 === 'number') {
// Fetch user by ID
console.log(`Fetching user by ID: ${param1}`);
return { id: param1, username: "user123", email: "[email protected]" }; // Simulated data
} else {
// Fetch users by username
console.log(`Fetching users by username: ${param1}`);
return [{ id: 1, username: param1, email: "[email protected]" }]; // Simulated data
}
}

// Usage
console.log(getUser(10));
console.log(getUser("john_doe"));
console.log(getUser(10, "john_doe"));
Original file line number Diff line number Diff line change
@@ -1,13 +1,22 @@
// no imports necessary up here now
// No imports necessary up here now

type ModuleCache = {
Analytics?: { Analytics: { recordEvent: (event: string) => void } };
UserManagement?: { UserManagement: { loadUserProfile: (userId: string) => void } };
};

const moduleCache: ModuleCache = {};

const recordBtn = document.getElementById('record-btn');
if (!recordBtn) {
console.error("Element with ID 'record-btn' not found.");
} else {
recordBtn.addEventListener('click', async () => {
try {
const { Analytics } = await import('./analytics');
Analytics.recordEvent('Button Clicked');
if (!moduleCache.Analytics) {
moduleCache.Analytics = await import('./analytics');
}
moduleCache.Analytics.Analytics.recordEvent('Button Clicked');
} catch (error) {
console.error("Failed to load the analytics module.", error);
}
Expand All @@ -20,8 +29,10 @@ if (!loadProfileBtn) {
} else {
loadProfileBtn.addEventListener('click', async () => {
try {
const { UserManagement } = await import('./userManagement');
UserManagement.loadUserProfile('user123');
if (!moduleCache.UserManagement) {
moduleCache.UserManagement = await import('./userManagement');
}
moduleCache.UserManagement.UserManagement.loadUserProfile('user123');
} catch (error) {
console.error("Failed to load the user management module.", error);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
function logClass(target) {
console.log(`Class in use: ${target.name}`);
}
let User = class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
};
User = __decorate([
logClass,
__metadata("design:paramtypes", [String, Number])
], User);
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ function logClass(target: Function) {
console.log(`Class in use: ${target.name}`);
}

//@logClass
@logClass
class User {
constructor(public name: string, public age: number) { }
}

Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
function logMethod(target, key, descriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args) {
const start = performance.now();
const result = originalMethod.apply(this, args);
const finish = performance.now();
console.log(`${key} executed in ${finish - start} milliseconds`);
return result;
};
return descriptor;
}
class MathOperations {
add(x, y) {
return x + y;
}
}
__decorate([
logMethod,
__metadata("design:type", Function),
__metadata("design:paramtypes", [Number, Number]),
__metadata("design:returntype", Number)
], MathOperations.prototype, "add", null);
const math = new MathOperations();
math.add(5, 3); // Output: "add executed in X milliseconds"
Loading

0 comments on commit 4ab56b2

Please sign in to comment.