首页 > 解决方案 > “未知”类型的参数不能分配给“字符串”类型的参数,使用 array.includes()

问题描述

有一些类似的问题,但我的情况不同。我正在使用文本编辑器,这是我的代码:

const LIST_TYPES = ["numbered-list", "bulleted-list"];


const toggleBlock = (editor: Editor, format: string) => {
  const isActive = isBlockActive(editor, format);
  const isList = LIST_TYPES.includes(format);
  // Wrap nodes at the specified location in the element container. If no location is specified, wrap the selection.
  Transforms.unwrapNodes(editor, {
    match: (n: Node) =>
      LIST_TYPES.includes(
        !Editor.isEditor(n) && SlateElement.isElement(n) && n.type
      ),
    split: true,
  });
  const newProperties: Partial<SlateElement> = {
    type: isActive ? "paragraph" : isList ? "list-item" : format,
  };
  Transforms.setNodes(editor, newProperties);

  if (!isActive && isList) {
    const block = { type: format, children: [] };
    Transforms.wrapNodes(editor, block);
  }
};

match()以 Node 作为参数。我通过了正确的类型。然而,在这个表达式!Editor.isEditor(n) && SlateElement.isElement(n) && n.type中,当我将鼠标悬停在每个语句上时.isEditor(n).isElement(n)n.type给出相同的警告:“'unknown' 类型的参数不可分配给 'string' 类型的参数”,即使我传递了正确的类型作为参数。我不明白“未知”来自哪里。

这是类型unwrapNodes()

unwrapNodes(editor: import("..").Editor, options: {
        at?: import("..").Path | import("..").Point | import("..").Range | undefined;
        match?: ((node: import("..").Node) => boolean) | undefined;
        mode?: "highest" | "lowest" | "all" | undefined;
        split?: boolean | undefined;
        voids?: boolean | undefined;
    }): void;

我认为问题在于includes(). 不知何故,它没有对此进行评估!Editor.isEditor(n) && SlateElement.isElement(n) && n.type。因为这有效: match: (n: Node) => LIST_TYPES.includes(n.type as string)

标签: reactjstypescript

解决方案


我想我只是通过包装逻辑语句并将其分配为字符串

Transforms.unwrapNodes(editor, {
    match: (n: Node) =>
      LIST_TYPES.includes(
        (!Editor.isEditor(n) && SlateElement.isElement(n) && n.type) as string
      ),
    split: true,
  });

推荐阅读