Skip to content

Instantly share code, notes, and snippets.

@ivawzh
Created July 8, 2020 21:57
Show Gist options
  • Select an option

  • Save ivawzh/9046e16351b1ca0e14fbc0c5e65d7bbd to your computer and use it in GitHub Desktop.

Select an option

Save ivawzh/9046e16351b1ca0e14fbc0c5e65d7bbd to your computer and use it in GitHub Desktop.
typescript inherit / extend multiple classes
interface User extends BaseUser, BaseEntity {}
class User {
public get fullName() : string {
return `${this.firstName} ${this.lastName}`
}
}
applyMixins(User, [BaseUser, BaseEntity])
function applyMixins(derivedCtor: any, baseCtors: any[]) {
baseCtors.forEach((baseCtor) => {
Object.getOwnPropertyNames(baseCtor.prototype).forEach((name) => {
const propertyDescriptor = Object.getOwnPropertyDescriptor(baseCtor.prototype, name)
if (!propertyDescriptor) throw new Error(`cannot find property descriptor of class ${baseCtor}`)
Object.defineProperty(
derivedCtor.prototype,
name,
propertyDescriptor
)
})
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment