回调函数中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);
MutationRecord[]
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;
}