Last active
December 8, 2023 02:12
-
-
Save hjJunior/a7ab4fa27cd20f8f7d891d71c868a2ab to your computer and use it in GitHub Desktop.
Typescript decorator
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 DecorateClass<T extends {}, D extends Decorator<T>> = new (object: T) => D; | |
type DecoratedObject<T extends {}, D extends Decorator<T>> = T & D; | |
const decoratorHasProp = (decorator: Decorator, prop: string | symbol): prop is keyof typeof decorator => { | |
return Object.getPrototypeOf(decorator).hasOwnProperty(prop); | |
}; | |
abstract class Decorator<T extends {} = {}> { | |
constructor(protected object: T) {} | |
static decorateObject<T extends {}, D extends Decorator<T>>( | |
object: T, | |
DecorateClass: DecorateClass<T, D>, | |
): DecoratedObject<T, D> { | |
const decorator = new DecorateClass(object); | |
const proxy = new Proxy(object, { | |
get(target: T, prop: string | symbol, receiver: any) { | |
if (decoratorHasProp(decorator, prop)) { | |
return decorator[prop]; | |
} | |
return Reflect.get(target, prop, receiver); | |
}, | |
}); | |
return proxy as T & D; | |
} | |
} |
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 UserData = { | |
firstName: string; | |
lastName: string; | |
} | |
class UserDecorator<T extends UserData = UserData> extends Decorator<T> { | |
get fullName(): string { | |
return `${this.object.firstName} ${this.object.lastName}`; | |
} | |
} | |
const user: UserData = { | |
firstName: "Helio", | |
lastName: "Junior", | |
}; | |
const decorated = Decorator.decorateObject(user, UserDecorator); | |
console.log(decorated.fullName); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Typescript playground