typescript - JSX 表达式中的空属性不再可分配给 "props"类型的 void

标签 typescript

我的 React 组件有以下声明,该组件曾经在 TypeScript 2.2 中编译,但现在在 TypeScript 2.3 中出现错误

class MyComponent extends React.Component<void, {}> {
  render() {
    return <div> Hello </div>
  }
}

// TS 2.3 : error TS2322: Type '{}' is not assignable to type 
// 'IntrinsicAttributes & IntrinsicClassAttributes<MyComponent> & Readonly<{ children?: ReactNode; }>...'.
//     Type '{}' is not assignable to type 'void'.
let m = <MyComponent />

最佳答案

类型参数应为 {},而不是使用 void

class MyComponent extends React.Component<{}, {}> {
  render() {
    return <div> Hello </div>
  }
}

在 TypeScript 2.3 中,空属性被视为空对象文字,这正是 React 对空 props 的行为方式。 TypeScript 2.3 现在也采用这种方式,因此当没有属性时,它会给出一个空对象文字类型。

关于typescript - JSX 表达式中的空属性不再可分配给 "props"类型的 void,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43663502/

相关文章:

typescript - 在 TypeScript 中导入 electron.BrowserWindow

javascript - 在 TypeScript 模块中使用 jQuery 扩展 AngularJS

typescript - 如何使用ts在vue3中的render函数中公开组件方法

angular - 导入 Angular 9 库时出现 "Value at position 4 in the NgModule.imports of MyCommonLibraryModule is not a reference"

angular - 如何在界面中定义angular的@Input装饰器?

javascript - PdfMake:函数 getBase64 返回未定义的值

javascript - 如何修复path.json不是一个函数

javascript - typescript 将 `interface` 键作为字符串的并集传播

node.js - 使用worker_threads的 typescript 配置

node.js - 在 MikroORM 中创建迁移时如何解决 EntityName.id 中的 "Please provide either ' 类型'或 'entity' 属性“错误?