【问题标题】:Argument of type 'unknown' is not assignable to parameter of type 'string', with array.includes()“未知”类型的参数不能分配给“字符串”类型的参数,使用 array.includes()
【发布时间】:2021-05-27 13:41:34
【问题描述】:

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

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) &amp;&amp; SlateElement.isElement(n) &amp;&amp; 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) &amp;&amp; SlateElement.isElement(n) &amp;&amp; n.type。因为这行得通: match: (n: Node) =&gt; LIST_TYPES.includes(n.type as string)

【问题讨论】:

  • 什么是Editor
  • 什么是 Transforms.unwrapNodes ?您能否分享可重现的示例?
  • @ritaj 我正在使用文本编辑器。 editor 代表文本编辑器中的完整文档。看起来我没有粘贴完整的功能。我更新问题
  • @captain-yossarian 我用 unwrapNodes 更新了这个问题。

标签: reactjs typescript


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-02
    • 1970-01-01
    • 2020-05-30
    • 1970-01-01
    • 2021-10-21
    • 2021-10-13
    • 2019-10-22
    相关资源
    最近更新 更多