what does <{}> mean at the end of extension in javascript?

Viewed 117

I encountered the following syntax in one of the tutorials for react-native. Declaration of the component which looks like:

export default class App extends Component<{}> {

//implementation

}

My question is: what does this <{}> mean and how does this declaration differ from this:

export default class App extends Component {

?

3 Answers

This is a typescript syntax and the what goes inside the <> is the type you expect the object to be.

That snippet is written in typescript. The <> syntax is used to specify a generic constraint on the component.

My advice is, if you're not using typescript, you can basically just ignore this notation when reading the tutorial. However, if you're interested in knowing more:

Here is documentation on typescript generics.

And here is some documentation on the Component class in react/react-native for typescript specifically.

Basically, a react component takes two generic arguments, one for the component's properties (this.props), and one for state (this.state).

Furthermore, {} is the type of an empty object with no properties, so this basically means that your component can be created without specifying any properties on it. You could use this component in JSX with just a simple <App />. You should note that by default, both props and state are simply {} so they don't need to specified manually as in your first snippet. Indeed, the first and second snippets are functionally identical (although only the second is valid jsx, the first requires typescript compilation).

Finally, while the other answer is correct, you should note that what goes inside the <> in this case is specifically the type of the component's 'props' object, accessed in the component via this.props. In general, a generic constraint may represent almost anything, but in this particular case, it is the type of the props.

As we're talking about react / react-native it's much more likely to be (facebook's) flow than typescript.

Their syntax is very similar, identical in this case, but flow is supported out of the box by RN's packager, typically uses .js extensions, and is much more prevalent in that ecosystem.

Either way, @CRice is correct about the meaning - it's a generic which in this case indicates the type of the class component's props.

Related