突变观察者回调函数中Mutation列表的打字稿类型是什么

What is the typescript type of Mutation list in callback function of mutation observer

提问人:Anjan Talatam 提问时间:4/8/2023 更新时间:4/8/2023 访问量:950

问:

回调函数中的打字稿类型是什么?mutationList

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);
javascript typescript 回调 mutation-observers

评论

0赞 Bergi 4/8/2023
呃,你有没有试过简单地检查类型声明?
1赞 Anjan Talatam 4/8/2023
嗨,当我在谷歌上搜索该类型时,我没有找到解决方案,但是后来我自己想通了。因此,我将其添加为问答,以便那些来stackoverflow寻找解决方案的人。我认为我们可以在stackoverflow上做到这一点
0赞 Bergi 4/8/2023
不要用谷歌搜索。在 TypeScript 附带的库声明中查找它,在本例中为 github.com/microsoft/TypeScript/blob/...
0赞 Anjan Talatam 4/8/2023
感谢您的添加,我想添加我的方法来获取类型。将鼠标悬停在 MutationObserver 上将向您显示回调的类型 () 将其分配给您的回调函数,然后将您带到我在答案中提到的类型声明。new MutationObserverMutationCallbackcmd+click
0赞 Bergi 4/8/2023
是的,这就是我的意思 - 只需在 IDE 中导航到 的类型声明,然后从那里导航到 的类型声明。无需谷歌搜索或在 stackoverflow 上询问。MutationObserverMutationCallback

答:

0赞 Anjan Talatam 4/8/2023 #1

突变记录[]

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;
}