Reputation: 20027
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.
Upvotes: 9
Views: 13063
Reputation: 3102
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.
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.
Upvotes: 10