打字稿:定义箭头功能的对象参数类型

时间:2019-04-25 17:12:20

标签: reactjs typescript

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

    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.

1 个答案:

答案 0 :(得分:0)

您可以使用type中的interface来完成此操作。

// 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',
);

关于两者之间的区别,您可以阅读this article

相关问题