【问题标题】:React + TypeScript: Type error on resize eventReact + TypeScript:调整大小事件的类型错误
【发布时间】:2021-12-17 19:13:34
【问题描述】:

另一个 React + TypeScript 事件处理程序问题。

如何修复这种类型的错误?

        const onResize = (
            event: React.UIEvent<Window, "resize">,
        ) => {
            console.log(event.target);
        };

        window.addEventListener("resize", onResize);

这会抛出

No overload matches this call.
  Overload 1 of 2, '(type: "resize", listener: (this: Window, ev: UIEvent) => any, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
    Argument of type '(event: React.UIEvent<Window, "resize">) => void' is not assignable to parameter of type '(this: Window, ev: UIEvent) => any'.
      Types of parameters 'event' and 'ev' are incompatible.
        Type 'UIEvent' is missing the following properties from type 'UIEvent<Window, "resize">': nativeEvent, isDefaultPrevented, isPropagationStopped, persist
  Overload 2 of 2, '(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions | undefined): void', gave the following error.
    Argument of type '(event: React.UIEvent<Window, "resize">) => void' is not assignable to parameter of type 'EventListenerOrEventListenerObject'.
      Type '(event: React.UIEvent<Window, "resize">) => void' is not assignable to type 'EventListener'.
        Types of parameters 'event' and 'evt' are incompatible.
          Type 'Event' is missing the following properties from type 'UIEvent<Window, "resize">': detail, view, nativeEvent, isDefaultPrevented, and 2 more.  TS2769

【问题讨论】:

    标签: reactjs typescript dom-events


    【解决方案1】:

    我认为在这种情况下你可以使用“事件”界面。

    const onResize = (
            event: Event,
        ) => {
            console.log(event.target);
        };
    

    类型 'Event' 缺少类型 'UIEvent' 中的以下属性

    这一行表示Event 类型(来自onResize)缺少UIEvent&lt;Window, "resize"&gt; 不提供的一些属性。

    编辑: 如果我们想访问像event.target.screen 这样的属性,你需要明确告诉 TypeScript 你的目标类型。

    做到这一点的方法是使用泛型类型将其转换为适当的类型:

    const onResize = (event: Event) => {
      const target = event.target as Window
      console.log(target.screen)
    }
    

    这会让 TypeScript 知道目标的类型是 window,这样它就会知道 screen 属性。

    【讨论】:

    • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
    • console.log(event.target.screen); 抛出 Property 'screen' does not exist on type 'EventTarget'.ts(2339)event 对象上的其他属性也会发生这种情况。 ://
    • 我明白了,在这种情况下,我认为您需要明确告诉 TypeScript 您的目标类型。这样做的方法是使用泛型类型将其转换为适当的类型:const onResize = (event: Event) =&gt; {const target = event.target as Window; console.log(target.screen)} 这将使 TypeScript 知道该元素的类型为 window 并且它将知道 screen 属性。我总是尽量避免强制转换类型,但在这种情况下,我找不到另一个可行的解决方案:/
    猜你喜欢
    • 1970-01-01
    • 2012-04-23
    • 1970-01-01
    • 2022-01-25
    • 2022-11-25
    • 1970-01-01
    • 2016-10-09
    • 2015-06-17
    • 2020-08-25
    相关资源
    最近更新 更多