Skip to content

Commit

Permalink
Merge branch '04_02' into 04_03
Browse files Browse the repository at this point in the history
  • Loading branch information
BrightBoost committed Jun 8, 2024
2 parents edc62e7 + 0fa792d commit b53a2c1
Show file tree
Hide file tree
Showing 19 changed files with 162 additions and 8 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"));

0 comments on commit b53a2c1

Please sign in to comment.