9

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.

3
  • What's wrong with myComponent: MyComponent ? Commented May 29, 2017 at 15:13
  • Nothing, it's just that the question is intended to correct my misunderstanding instead, not to make the code work. Commented May 29, 2017 at 15:14
  • 1
    Well, implements and extends only work for classes and interfaces, you can't use them for variables Commented May 29, 2017 at 15:15

1 Answer 1

10

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.

Sign up to request clarification or add additional context in comments.

2 Comments

amazing, thank you! Can you elaborate on why implements won't work in this case, for dummies?
@lustoykov I have added an explaination about why I think they chose for this syntax.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.