Created
June 9, 2019 10:58
-
-
Save hasparus/1fa68df920ab388715685f263e03d621 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Constructor<T, Args extends any[]> = { | |
new (...args: Args): T; | |
(...args: Args): T; | |
}; | |
function makeConstructor<T, Args extends any[], P = {}>( | |
create: (...args: Args) => T, | |
prototype?: P & ThisType<T & P> | |
) { | |
const constructor = function(this: T | undefined, ...args: Args) { | |
if (this instanceof constructor) { | |
return Object.assign(this, create(...args)); | |
} | |
return new constructor(...args); | |
} as Constructor<T & P, Args>; | |
constructor.prototype = prototype || {}; | |
return constructor; | |
} | |
type CharacterStats = { | |
strength: number; | |
wisdom: number; | |
charisma: number; | |
}; | |
const Character = makeConstructor( | |
(characterName: string, stats: CharacterStats) => ({ | |
// instance | |
characterName, | |
stats, | |
level: 1, | |
}), | |
{ | |
// prototype | |
__brand: "Character" as const, | |
sayHello() { | |
console.log( | |
"Hi, I'm", | |
this.characterName, | |
this.level, | |
this.stats, | |
this.sayHello, | |
this | |
); | |
}, | |
} | |
); | |
type Character = ReturnType<typeof Character>; | |
const merlin = Character("Merlin", { charisma: 6, wisdom: 10, strength: 2 }); | |
const kingArthur = new Character("King Arthur", { | |
charisma: 7, | |
strength: 9, | |
wisdom: 5, | |
}); | |
merlin.sayHello(); | |
kingArthur.sayHello(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment