Advertisement
Guest User

Untitled

a guest
Jun 20th, 2019
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. type Constructor<T, Args extends any[]> = {
  2. new (...args: Args): T;
  3. (...args: Args): T;
  4. };
  5.  
  6. function makeConstructor<T, Args extends any[], P = {}>(
  7. create: (...args: Args) => T,
  8. prototype?: P & ThisType<T & P>
  9. ) {
  10. const constructor = function(this: T | undefined, ...args: Args) {
  11. if (this instanceof constructor) {
  12. return Object.assign(this, create(...args));
  13. }
  14. return new constructor(...args);
  15. } as Constructor<T & P, Args>;
  16.  
  17. constructor.prototype = prototype || {};
  18. return constructor;
  19. }
  20.  
  21. type CharacterStats = {
  22. strength: number;
  23. wisdom: number;
  24. charisma: number;
  25. };
  26.  
  27. const Character = makeConstructor(
  28. (characterName: string, stats: CharacterStats) => ({
  29. // instance
  30. characterName,
  31. stats,
  32. level: 1,
  33. }),
  34. {
  35. // prototype
  36. __brand: "Character" as const,
  37. sayHello() {
  38. console.log(
  39. "Hi, I'm",
  40. this.characterName,
  41. this.level,
  42. this.stats,
  43. this.sayHello,
  44. this
  45. );
  46. },
  47. }
  48. );
  49.  
  50. type Character = ReturnType<typeof Character>;
  51.  
  52. const merlin = Character("Merlin", { charisma: 6, wisdom: 10, strength: 2 });
  53. const kingArthur = new Character("King Arthur", {
  54. charisma: 7,
  55. strength: 9,
  56. wisdom: 5,
  57. });
  58.  
  59. merlin.sayHello();
  60. kingArthur.sayHello();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement