Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

myComponent: Component<IProps, IState> implements MyInterface, but this won't work and I have no idea why.

Can somebody clarify? I'm just starting with TypeScript and can't figure this out. What would be an alternative to that?


Please note: myComponent: MyComponent is not what I'm looking for as an answer. I want to correct my misunderstanding of TypeScript instead.

like image 768
Lyubomir Avatar asked May 29 '17 15:05

Lyubomir


1 Answers

TypeScript offers something that is called intersection types. 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 uses this syntax instead of the implements syntax most likely because it matches more closely to the union type.

myComponent: Component<IProps, IState> | MyInterface

The above type means: Object must be of type Component<IProps, IState> or implement the MyInterface interface. 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 as it may be, the & and | tokens are also used as the bitwise AND and OR operators.

like image 52
Wazner Avatar answered Sep 19 '22 12:09

Wazner