Created
October 2, 2021 06:31
-
-
Save mmyoji/5f855055c774f452b3b2be76fb964c2b to your computer and use it in GitHub Desktop.
Meta programming in TypeScript
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
class User { | |
name: string; | |
age: number; | |
#createdAt: Date; | |
constructor(name: string, age: number) { | |
this.name = name; | |
this.age = age; | |
this.#createdAt = new Date(); | |
} | |
get profile(): string { | |
return `Name: ${this.name}, Age: ${this.age} (created: ${this.#createdAt})`; | |
} | |
hello(): string { | |
return `${this.#helloPrefix()}, I'm ${this.name}!`; | |
} | |
#helloPrefix(): string { | |
return "Hi"; | |
} | |
} | |
class AdminUser extends User {} | |
const log = console.log; | |
(function main() { | |
const user = new User("bob", 20); | |
// Get a class from an instance | |
log(user.constructor === User); | |
//=> true | |
// Get a class name as string | |
// @returns {string} | |
log(User.name); | |
//=> "User" | |
// Get public methods | |
// @returns {string[]} | |
log(Object.getOwnPropertyNames(User.prototype)); | |
//=> ["constructor", "profile", "hello"] | |
// Get public properties | |
// @returns {string[]} | |
log(Object.getOwnPropertyNames(user)); | |
//=> ["name", "age"] | |
// Get an ancestor | |
// I'm not sure this is correct in any cases. | |
log(Object.getPrototypeOf(AdminUser) === User); | |
//=> true | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment