score:8

Accepted answer

It's fairly easy to implement the second variant — the one where an explicit type argument is required:

Solution one

import * as React from 'react';

type Props<K extends keyof JSX.IntrinsicElements> = JSX.IntrinsicElements[K];

declare class MyComponent<K extends keyof JSX.IntrinsicElements> extends React.Component<Props<K>> {}

<MyComponent<'a'> href="https://example.com/" id="myLink" />;

Solution two

When it comes to the first variant, it's more tricky. What you want is not a generic component, but a union of props. To illustrate why, let's consider a concrete example when MyComponent handles only a union of a and button.

import * as React from 'react';

type Props =
   | ({ as: 'a' } & JSX.IntrinsicElements['a'])
   | ({ as: 'button' } & JSX.IntrinsicElements['button']);

declare class MyComponent<T extends 'a' | 'button'> extends React.Component<Props> {}

<MyComponent as="a" href="https://example.com" />; // ✔ OK
<MyComponent as="button" href="https://example.com" />; // ✘ Compile-time error

MyComponent doesn't have to be generic in order to recognize which props it should receive. The as prop is a sufficient discriminant.

We can generalize this example by creating a union of all tags and their respective props:

import * as React from 'react';

type Props = {
  [K in keyof JSX.IntrinsicElements]: { as: K } & JSX.IntrinsicElements[K];
}[keyof JSX.IntrinsicElements];

declare class MyComponent extends React.Component<Props> {}

<MyComponent as="a" href="https://example.com" />; // ✔ OK
<MyComponent as="button" href="https://example.com" />; // ✘ Compile-time error

This will get the job done, as it's the same as if we defined our union manually. However, creating such a huge union has downsides:

  • IntelliSense becomes painfully slow
  • Error messages become cryptic
  • The overall complexity increases.

Just something to be aware of! ;)


Related Query

More Query from same tag