[英]Typescript - return type that is part of whole interface (check if it implements other interface)
[英]TypeScript & React - Component implements interface - use as a type?
假設我有以下組件
class MyComponent extends
React.Component<IProps, IState> implements MyInterface {...}
現在我想說一些變量是一個React.Component
的instance
,它有IProps, IState
和implements MyInterface
,類似於
myComponent: Component<IProps, IState> implements MyInterface
,但這不起作用,我不明白為什么。
有人可以澄清一下嗎? 我剛開始使用TypeScript而無法解決這個問題。 有什么可以替代呢?
請注意: myComponent: MyComponent
不是我想要的答案。 我想糾正我對TypeScript的誤解。
TypeScript提供了一種稱為交集類型的東西。 這允許您組合多種類型。
在你的情況下,它將是這樣的:
myComponent: Component<IProps, IState> & MyInterface.
注意:我不知道TypeScript為什么選擇這種語法,下面只是我猜測為什么我認為他們可能選擇這種語法。
TypeScript最有可能使用此語法而不是implements
語法,因為它更接近於union類型。
myComponent: Component<IProps, IState> | MyInterface
上述類型表示:對象必須是Component<IProps, IState>
類型Component<IProps, IState>
或者實現MyInterface
接口。 對於TypeScript,類和類之間的區別非常小。 類類型只不過是具有構造函數字段的接口。
而且可能是&
和|
標記也用作按位AND和OR運算符。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.