ฉันจะสามารถใช้งานฟังก์ชัน makeWatchedObject ในเอกสาร TypeScript ได้อย่างไร?
https://www.typescriptlang.org/docs/handbook/2/template-literal-types.html
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 => {
(parameter) newName: string
console.log(`new name is ${newName.toUpperCase()}`);
});
person.on("ageChanged", newAge => {
(parameter) newAge: number
if (newAge < 0) {
console.warn("warning! negative age");
}
})
เมื่อฉันรันตัวอย่างนี้โดยใช้ Node เกิดข้อผิดพลาด:
ReferenceError: makeWatchedObject ไม่ได้ถูกกำหนด
ฉันกำลังพยายามจะใช้งานฟังก์ชันนี้ แต่ฉันล้มเหลว
ฉันได้ค้นหาแล้ว แต่ไม่มีใครมีข้อสงสัยเหมือนกัน
ใครช่วยฉันได้บ้าง?
คำตอบ #1
คำตอบของคุณทำให้ฉันได้รับแรงบันดาลใจมาก ฉันลองทำตามมันโดยไม่ใช้ประเภทก่อน
function makeWatchedObject(obj) {
const cache = new Map()
const on = (change, callback) => {
cache.set(change.replace("Changed", ""), callback)
}
return new Proxy({
...obj,
on: on
}, {
set: (target, p, newValue) => {
cache.get(p)(newValue)
return true
}
})
}
แล้วฉันก็พยายามเพิ่มประเภทให้มัน
function makeWatchedObject<Type>(obj: Type): Type & PropEventSource<Type> {
const cache = new Map<string | symbol, (newValue: any) => void>()
const on = (change:string | symbol, callback: (newValue: any) => void) => {
cache.set(typeof change === "string" ? change.replace("Changed", "") : change, callback)
}
return new Proxy<Type & PropEventSource<Type>>({
...obj,
on: on
}, {
set: (target: Type, p: string | symbol, newValue: any) => {
cache.get(p)?.(newValue)
return true
}
})
}
ในฐานะเป็นแบ็กเอนด์ การใช้งานค่อนข้างตรงไปตรงมา แต่ก็ใช้งานได้ >.<
