Skip to content

Instantly share code, notes, and snippets.

@lynsei
Created October 22, 2023 19:02
Show Gist options
  • Save lynsei/ab5dbfa840ee518ebf5ee0f9922a349b to your computer and use it in GitHub Desktop.
Save lynsei/ab5dbfa840ee518ebf5ee0f9922a349b to your computer and use it in GitHub Desktop.
Property event change
type PropEventSource<Type> = {
on<Key extends string & keyof Type>
(eventName: `${Key}Changed`, callback: (newValue: Type[Key]) => void): void;
};
declare function makeWatchedObject<Type>(obj: Type): Type & PropEventSource<Type>;
const person = makeWatchedObject({
firstName: "lynsei",
lastName: "asynyn",
age: 32
});
person.on("firstNameChanged", newName => {
console.log(`new name is ${newName.toUpperCase()}`);
});
person.on("ageChanged", newAge => {
if (newAge < 0) {
console.warn("warning! negative age");
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment