Lyu*_*mir 5 typescript reactjs
假设我有以下组件
class MyComponent extends
React.Component<IProps, IState> implements MyInterface {...}
Run Code Online (Sandbox Code Playgroud)
现在我想说的是,有些变量是一个instance
的React.Component
有IProps, IState
和implements MyInterface
,像
myComponent: Component<IProps, IState> implements MyInterface
,但这不起作用,我不知道为什么.
有人可以澄清一下吗?我刚开始使用TypeScript而无法解决这个问题.有什么可以替代呢?
请注意:
myComponent: MyComponent
不是我要找的答案.我想纠正我对TypeScript的误解.
TypeScript提供了一种称为交集类型的东西.这允许您组合多种类型.
在你的情况下,它将是这样的:
myComponent: Component<IProps, IState> & MyInterface.
Run Code Online (Sandbox Code Playgroud)
注意:我不知道TypeScript为什么选择这种语法,下面只是我猜测为什么我认为他们可能选择这种语法.
TypeScript使用此语法而不是implements
语法,因为它更接近于union类型.
myComponent: Component<IProps, IState> | MyInterface
Run Code Online (Sandbox Code Playgroud)
上述类型表示:对象必须是类型Component<IProps, IState>
或实现MyInterface
接口.对于TypeScript,类和类之间的区别非常小.类类型只不过是具有构造函数字段的接口.
并且可能是,&
和|
令牌也用作按位AND和OR运算符.
归档时间: |
|
查看次数: |
4079 次 |
最近记录: |