如何在Typescript中将空接口指定为通用参数?

问题描述

我在Typescript中有一个React组件。该组件具有状态,但没有属性我有以下代码

interface State { ... }

class MyComponent extends React.Component<{},State> { ... }

今天我从tslint移到eslint,并得到警告,说我不应该使用{}作为类型。

当我创建一个空接口时:

interface Prop { }

并将其作为第一个通用参数传递给我,另一个警告是,空接口与{}相同。

那我该怎么办?我不能使用never,因为它会引起很多其他错误-在这里确实没有意义。除了禁用ban-types规则,还有其他选择吗?

解决方法

假设您希望该组件能够成为其他组件的父对象,那么即使它没有其他道具,您可能仍想接受children键。

您的代码将如下所示,并且不会为道具传递空规范...

class MyComponent extends React.Component<{ children?: ReactNode },State> { ... }