I'm just trying to learn typesript and have a problem. I can't figure out how declare function
works in ts.
The TS documentation has a section about Template Literal Types.
It has the following code:
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: "Saoirse",
lastName: "Ronan",
age: 26
});
person.on("firstNameChanged", newName => {
console.log(`new name is ${newName.toUpperCase()}`);
});
person.on("ageChanged", newAge => {
if (newAge < 0) {
console.warn("warning! negative age");
}
})
// this is my console.log
console.log(person.firstName);
Сompiles to this js code:
var person = makeWatchedObject({
firstName: "Saoirse",
lastName: "Ronan",
age: 26
});
person.on("firstNameChanged", function (newName) {
console.log("new name is ".concat(newName.toUpperCase()));
});
person.on("ageChanged", function (newAge) {
if (newAge < 0) {
console.warn("warning! negative age");
}
});
// this is my console.log
console.log(person.firstName);
I'm trying to run it and I get this error: enter image description here
Could you explain to me what I'm doing wrong? Why is declare function ignored? Thank you.