Generic Type Arguments in JSX Elements

Typescript recently released generic type arguments for JSX in their 2.9 release. It's a mouthfull, but what does that mean for us? A common use-case I'm excited for is allowing consumers of libraries to extend a component's props. Using dynamic components we'll look at allowing our components to be extended even more.

What Are Generic Type Arguments?

As shown in the Typescript release notes, generic type arguments are a way to create components using Typescript's generics syntax. Below is a side-by-side comparison of the old way vs. using generic type arguments.

The Old Way:

// Notice color isn't defined as a prop, and will error out normallyfunctionDiv(props:{ value: string }){const{ value,...rest }=this.props;return<div{...rest}/>;}// Using spread, we can trick Typescript into ignoring that color will be a prop// on DivfunctionApp(){return<Div {...{ color:"red"}}/>;}

MenuItem works perfect fine as a component, but when it's time to add additional properties, Typescript will yell. For example, the a tag needs a href prop. We don't want to hardcode href, because we can inject any type of element through the tag prop (React Router, button, etc).

<MenuItemtag="a"href="http://google.com">Click Me!</MenuItem>// Error because href isn't defined in IProps!<MenuItemtag={Link}to="/home">Home</MenuItem>// Error because to isn't defined in IProps!