Skip to content

Instantly share code, notes, and snippets.

@EricsonWillians
Last active September 28, 2023 17:03
Show Gist options
  • Save EricsonWillians/8f97c29515c643196f65ccf14e11e469 to your computer and use it in GitHub Desktop.
Save EricsonWillians/8f97c29515c643196f65ccf14e11e469 to your computer and use it in GitHub Desktop.
Stherzada Generics
interface Skills {
[language: string]: 'Beginner' | 'Intermediate' | 'Expert' | 'Unknown';
}
// A mixin to add coding ability
type Coder = {
codeIn(language: string): void;
};
function CodingMixin<T extends Skills>(base: new (...args: any[]) => { skills: T }): any & Coder {
return class extends base implements Coder {
codeIn(language: string): void {
const proficiency = this.skills[language] || "Unknown";
console.log(`${this.name} codes in ${language}. Proficiency: ${proficiency}`);
}
};
}
// A decorator to log expertise upon method call
function Greet(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function(...args: any[]) {
console.log(`Hello, my name is ${this.name}.`);
originalMethod.apply(this, args);
};
return descriptor;
}
class VersatilePerson<T extends Skills> {
constructor(public name: string, public age: number, public skills: T) {}
@Greet
displaySkills(): this {
console.log(`My coding skills include: ${JSON.stringify(this.skills)}`);
return this; // for chaining
}
introduce(): this {
console.log(`I am ${this.age} years old.`);
return this; // for chaining
}
}
const EnhancedCoder = CodingMixin(VersatilePerson);
const stherzada = new EnhancedCoder('Stherzada', 25, {
TypeScript: 'Expert',
JavaScript: 'Intermediate',
Python: 'Beginner'
});
stherzada.displaySkills().introduce().codeIn('TypeScript').codeIn('JavaScript').codeIn('Python');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment