Created
October 22, 2023 19:02
-
-
Save lynsei/ab5dbfa840ee518ebf5ee0f9922a349b to your computer and use it in GitHub Desktop.
Property event change
This file contains 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 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