reactjs - TypeScript & React - 组件实现接口(interface) - 用作类型?

标签 reactjs typescript

假设我有以下组件

class MyComponent extends 
React.Component<IProps, IState> implements MyInterface {...}

现在我想说一些变量是 instanceReact.ComponentIProps, IStateimplements MyInterface , 类似

myComponent: Component<IProps, IState> implements MyInterface ,但这行不通,我不知道为什么。

有人可以澄清一下吗?我刚开始使用 TypeScript,无法弄清楚。 有什么替代方案?


请注意: myComponent: MyComponent不是我要找的答案。我想改正我对 TypeScript 的误解。

最佳答案

TypeScript 提供了一种称为交集类型的东西。这允许您组合多种类型。

在你的情况下它会是这样的:

myComponent: Component<IProps, IState> & MyInterface.

typescript doc

为什么是这个语法?

注意:我不知道为什么 TypeScript 选择了这种语法,下面只是我对为什么我认为他们可能选择这种语法的猜测。

TypeScript 使用此语法而不是 implements语法最有可能是因为它更接近于联合类型。

myComponent: Component<IProps, IState> | MyInterface

上面的类型表示:对象的类型必须是Component<IProps, IState>或实现 MyInterface界面。对于 TypeScript,类和接口(interface)在类型上的区别非常小。类类型只不过是具有构造函数字段的接口(interface)。

事实上,&|标记也用作按位 AND 和 OR 运算符。

关于reactjs - TypeScript & React - 组件实现接口(interface) - 用作类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44245607/

相关文章:

javascript - ReactJS + Redux,出现错误 "Failed prop type: Right-hand side of ' instanceof' is not callable”

reactjs - 路径路由 : Application Load Balancer for React Application

angular - 有没有办法防止 formControl 触发事件?

javascript - 文件切换 js 在 Angular 6 中不起作用

css - 如何使用 React 获取 CSS 内容上的当前 URL?

javascript - React-router:如果 <Link> 处于事件状态,如何禁用它?

javascript - 如何通过react在express上向mailchimp发送post请求

angular - 如何将 FormGroup 对象作为输出从子组件 n Angular 发送到父组件

node.js - NestJS 将 @Query() 反序列化为具有复杂类型的 DTO

javascript - Angular 通用意外 token { 在 npm run start :ssr 上