【问题标题】:How to write types for a nested function in a destructured object?如何为解构对象中的嵌套函数编写类型?
【发布时间】:2019-09-06 08:22:44
【问题描述】:

我正在尝试为bodyheaderfooter 编写类型,但找不到访问它的方法。通常我在对象被解构时会遇到这类问题。

来自bodyheaderfooter 我收到错误消息: “常量体:任何。 类型“{}”上不存在属性“body”。”

interface ModalProps {
  onClick: () => void;
 
}

const Modal: React.FunctionComponent<ModalProps> = props => {
  useContext(ModalContext);
  const [isOpen, setIsOpen] = useState(false);
  const [content = {}, setContent] = useState({});
  const show = (content = {}) => {
    const { body, header, footer } = content;
    if (!body && !header && !footer) {
      setContent({ content });
    } else {
      setContent({ body, header, footer });
    }
    setIsOpen(true);
  };

我尝试将其插入界面但没有成功:

interface ModalProps {
  onClick: () => void;
     content: {
     body: any
     }
 
}

也试过了:

const { body, header, footer }: {body: any, header: any, footer: any} = content;

但收到错误消息:“类型 '{}' 缺少来自类型 '{ body: any; header: any; footer: any; }': body, header, footer 的以下属性

任何提示将不胜感激。谢谢!

【问题讨论】:

    标签: typescript typescript-typings


    【解决方案1】:

    现在,show 函数中的 content{} 类型,因为你没有告诉 TypeScript 任何不同的东西,这就是它可以从参数默认值 ({}) 推断出的全部内容。 {} 类型没有body 等。

    你需要告诉 TypeScript content 是什么。我猜测您想要 content 是什么,但您可能是这样的:

    interface Content {
      body?: string;
      header?: string;
      footer?: string;
      content?: Content;
    }
    

    那么setContent 将是:

    function setContent(content: Content) {
      // ...
    }
    

    show 将是:

    const show = (content: Content = {}) => {
      const { body, header, footer } = content;
      if (!body && !header && !footer) {
        setContent({ content });
      } else {
        setContent({ body, header, footer });
      }
    };
    

    然而,让setContent 必须处理与show 必须处理的相同的事情似乎有点奇怪(检查是否有bodyheaderfooter 值或者只是一个 content 值)。重载setContent 可能会更好。

    【讨论】:

      【解决方案2】:

      我相信问题出在你在 show 函数上的默认 contentconst show = (content = {}) =&gt; {

      这会导致内容成为空对象的可能性。这就是为什么您会收到“类型 '{}' 上不存在属性 'body'。”。 Typescript 推断 body 可能不存在于您的对象 content 中。

      如果你不打算在没有参数的情况下调用 show,你可以简单地删除你的默认值。另一方面,如果你想输入你的 show 函数,你可以做这个界面:

      type RawContent = String;
      interface ContentWithHeaderAndFooter {
       header: any;
       body: any;
       footer: any;
      }
      type Content = RawContent | ContentWithHeaderAndFooter;
      const show = (content: Content) => {...}
      

      我相信这将涵盖您所有的用例,但对我来说,这有点矫枉过正,我会简单地删除 show 函数的默认值。

      【讨论】:

        猜你喜欢
        • 2022-01-22
        • 2017-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-28
        • 2015-12-22
        • 2022-01-08
        • 2019-10-25
        相关资源
        最近更新 更多