简体   繁体   English

TypeScript&React - 组件实现接口 - 用作类型?

[英]TypeScript & React - Component implements interface - use as a type?

Let's say I have the following component 假设我有以下组件

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

Now I want to say that some variable is an instance of a React.Component that has IProps, IState and implements MyInterface , something like 现在我想说一些变量是一个React.Componentinstance ,它有IProps, IStateimplements MyInterface ,类似于

myComponent: Component<IProps, IState> implements MyInterface , but this won't work and I have no idea why. myComponent: Component<IProps, IState> implements MyInterface ,但这不起作用,我不明白为什么。

Can somebody clarify? 有人可以澄清一下吗? I'm just starting with TypeScript and can't figure this out. 我刚开始使用TypeScript而无法解决这个问题。 What would be an alternative to that? 有什么可以替代呢?


Please note: myComponent: MyComponent is not what I'm looking for as an answer. 请注意: myComponent: MyComponent不是我想要的答案。 I want to correct my misunderstanding of TypeScript instead. 我想纠正我对TypeScript的误解。

TypeScript offers something that is called intersection types. TypeScript提供了一种称为交集类型的东西。 This allows you to combine multiple types. 这允许您组合多种类型。

In your case it would be something like: 在你的情况下,它将是这样的:

myComponent: Component<IProps, IState> & MyInterface.

typescript doc 打字稿文件

Why this syntax? 为什么这个语法?

Notice: I don't know why TypeScript chose for this syntax, below is only my speculation about why I think they might have chosen for this syntax. 注意:我不知道TypeScript为什么选择这种语法,下面只是我猜测为什么我认为他们可能选择这种语法。

TypeScript uses this syntax instead of the implements syntax most likely because it matches more closely to the union type. TypeScript最有可能使用此语法而不是implements语法,因为它更接近于union类型。

myComponent: Component<IProps, IState> | MyInterface

The above type means: Object must be of type Component<IProps, IState> or implement the MyInterface interface. 上述类型表示:对象必须是Component<IProps, IState>类型Component<IProps, IState>或者实现MyInterface接口。 For TypeScript, the distinction between classes and interfaces in types is quite small. 对于TypeScript,类和类之间的区别非常小。 A class type is nothing more than an interface with a constructor field. 类类型只不过是具有构造函数字段的接口。

And as it may be, the & and | 而且可能是&| tokens are also used as the bitwise AND and OR operators. 标记也用作按位AND和OR运算符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM