回调函数中
mutationList
的typescript类型是什么?
const targetNode = document.getElementById("some-id");
const config = { attributes: true, childList: true, subtree: true };
const callback = (mutationList, observer) => {
for (const mutation of mutationList) {
if (mutation.type === "childList") {
console.log("A child node has been added or removed.");
} else if (mutation.type === "attributes") {
console.log(`The ${mutation.attributeName} attribute was modified.`);
}
}
};
const observer = new MutationObserver(callback);
observer.observe(targetNode, config);
const callback = (mutationList: MutationRecord[], observer: MutationObserver) => {
for (const mutation of mutationList) {
if (mutation.type === "childList") {
console.log("A child node has been added or removed.");
} else if (mutation.type === "attributes") {
console.log(`The ${mutation.attributeName} attribute was modified.`);
}
}
};
或
const callback: MutationCallback = (mutationList, observer) => {
for (const mutation of mutationList) {
if (mutation.type === "childList") {
console.log("A child node has been added or removed.");
} else if (mutation.type === "attributes") {
console.log(`The ${mutation.attributeName} attribute was modified.`);
}
}
};
推荐:为回调函数分配一个类型,而不是为每个参数分配一个类型。
interface MutationCallback {
(mutations: MutationRecord[], observer: MutationObserver): void;
}