繁体   English   中英

打字稿:为箭头函数的对象参数定义类型

[英]Typescript: Define type for object param of arrow function

我试图在箭头函数中定义对象参数的类型,我是打字稿的新手,我确实找到了任何显示这种情况的例子。 所以:

    const audioElem = Array.from(videoElem.parentNode.childNodes).find(
      (child: {tagName: string}): boolean => child.tagName === 'AUDIO',
    );

我只是收到一个错误,这很正常,但您明白了。 任何的想法 ? :)

错误:

error TS2345: Argument of type '(child: { tagName: string; }) => boolean' is not assignable to parameter of type '(value: {}, index: number, obj: {}[]) => boolean'.
  Types of parameters 'child' and 'value' are incompatible.
    Property 'tagName' is missing in type '{}' but required in type '{ tagName: string; }'.

17       (child: { tagName: string }): boolean => child.tagName === 'AUDIO',
         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  src/components/Subscriber/Subscriber.tsx:17:17
    17       (child: { tagName: string }): boolean => child.tagName === 'AUDIO',
                       ~~~~~~~
    'tagName' is declared here.

您可以使用一个typeinterface来做到这一点。

// Either…
type MyParam = {
  tagName: string
}

// … or…
interface MyParam {
  tagName: string
}

// …and then.
const audioElem = Array.from(videoElem.parentNode.childNodes).find(
  (child: MyParam): boolean => child.tagName === 'AUDIO',
);

至于两者的区别,可以看这篇文章

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM