类型错误:后续变量声明必须具有相同的类型。变量'e'必须是"any"类型,但此处的类型为 'Event'



我正在尝试构建项目,并希望将其部署到vercel,但遇到了一些类型错误。

该网站在开发中运行良好(使用yarn dev(。

这是我用来关闭模态而不传播事件的两个函数。

//Closes the modal
const exitModal = (e) => {
closeModal(false)
//this part stops the click from propagating
if (!e) var e = window.event
e.cancelBubble = true
if (e.stopPropagation) e.stopPropagation()
}
const exitAndRefresh = (e) => {
exitModal(e)
window.location.reload()
}

下面的JSX带有onClick功能:

<button
className="absolute z-10 top-0 right-0 mt-1 mr-2 p-2 rounded-lg text-white bg-red-500 hover:bg-red-700"
onClick={exitModal}
>
Cancel
</button>

构建错误:(使用纱线构建(

Type error: Subsequent variable declarations must have the same type.  Variable 'e' must be of type 'any', but here has type 'Event'.
91 |
92 |     //this part stops the click from propagating
> 93 |     if (!e) var e = window.event
|                 ^
94 |     e.cancelBubble = true
95 |     if (e.stopPropagation) e.stopPropagation()
96 |   }

我试过这样做-

//Closes the modal
const exitModal = (e: Event) => {
closeModal(false)
//this part stops the click from propagating
if (!e) var e = window.event
e.cancelBubble = true
if (e.stopPropagation) e.stopPropagation()
}
const exitAndRefresh = (e: Event) => {
exitModal(e)
window.location.reload()
}

但是得到了这个错误:

Type error: Type '(e: Event) => void' is not assignable to type 'MouseEventHandler<HTMLButtonElement>'.
Types of parameters 'e' and 'event' are incompatible.
Type 'MouseEvent<HTMLButtonElement, MouseEvent>' is missing the following properties from type 'Event': cancelBubble, composed, returnValue, srcElement, and 7 more.
158 |               <button
159 |                 className="absolute z-10 top-0 right-0 mt-1 mr-2 p-2 rounded-lg text-white bg-red-500 hover:bg-red-700"
> 160 |                 onClick={exitModal}
|                 ^
161 |               >
162 |                 Cancel
163 |               </button>
error Command failed with exit code 1.

这个片段是一个过时的片段,它停止了传播(跨浏览器(:

//this part stops the click from propagating
if (!e) var e = window.event
e.cancelBubble = true
if (e.stopPropagation) e.stopPropagation()

就我个人而言,我认为我们不应该通过包含额外的代码来间接支持IE…

但无论如何,你不需要var

//  const exitModal = (e: Event) => {
//                      ^^^^^^^ don't forget to annotate
e ??= window.event!; // if e is not there set it to window.event
e.cancelBubble = true;
e.stopPropagation?.(); // if stopPropagation exists call it

感叹号是用来告诉TypeScript window.event的存在。

这段代码使用了JavaScript的最新功能:取消合并赋值和函数调用的可选链接。

由于您使用的是带有NextJS的隐式构建系统,因此您可以直接使用这些系统,而不必担心旧的浏览器。

最新更新