DEV Community

Discussion on: Typing React Props in TypeScript

Collapse
lukeshiru profile image
LUKESHIRU

One thing you can do instead of using HTMLProps and having to know the actual type of every HTML tag, is to use JSX.IntrinsicElements this way:

JSX.IntrinsicElements["div"]; // All properties of a "div"
JSX.IntrinsicElements["span"]; // All properties of a "span"
JSX.IntrinsicElements["input"]; // You guested it! All properties of an "input"
Enter fullscreen mode Exit fullscreen mode

So your example could be something like this:

import { FC } from "react";

export type PostPreviewProps =
    JSX.IntrinsicElements["div"] & {
        // I used "heading" here because
        // "title" is already a prop of "div"
        readonly heading?: string;
    };

export const PostPreview: FC<PostPreviewProps> = ({
    children,
    heading,
    ...props
}) => (
    <div {...props}>
        <h1>{heading}</h1>
        {children}
    </div>
);
Enter fullscreen mode Exit fullscreen mode

Cheers!

Collapse
bennycode profile image
Benny Neugebauer Author

Thank you for sharing this solution with us! 🙂 Since the "title" attribute really is a global HTML element attribute, I will also update my tutorial to use "heading" instead of "title". 👍