TypeScript & React - Component implements an interface - is it used 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 instance

for React.Component

, which has IProps, IState

and implements MyInterface

, something like

myComponent: Component<IProps, IState> implements MyInterface

but it won't work and I have no idea why.

Can anyone clarify? I'm just starting out with TypeScript and can't figure it out. What would be the alternative to this?


Please note: myComponent: MyComponent

not what I'm looking for as an answer. I want to correct my misunderstanding of TypeScript.

+3


source to share


1 answer


TypeScript offers something called intersection types. This allows several types to be combined.

In your case, it would be something like:

myComponent: Component<IProps, IState> & MyInterface.

      

TypeScript doc

Why this syntax?



Note. I don't know why TypeScript chose this syntax, below are just my suggestions as to why I think they might have chosen this syntax.

TypeScript uses this syntax instead of syntax implements

, most likely because it is more closely related to the union type.

myComponent: Component<IProps, IState> | MyInterface

      

The above type means: the object must have a type Component<IProps, IState>

or implement an interface MyInterface

. For TypeScript, the distinction between classes and interfaces in types is quite small. A class type is nothing more than an interface with a constructor field.

And how else, markers &

and |

are also used as bitwise operators AND and OR.

+5


source







All Articles