DEV Community

Discussion on: Understanding React Proptypes

Collapse
lukeshiru profile image
Luke Shiru • Edited on

Worth mentioning that you can achieve a good DX without new dependencies using JSDocs:

// @ts-check

/** @type {import("react").VFC<{ name: string; age: number }>} */
export const Example = ({ name, age }) => (
    <h3>
        {name} will be {age + 3} years old in 3 years!
    </h3>
);
Enter fullscreen mode Exit fullscreen mode

If you try to use Example, you'll get autocompletion of name and age in your editor, if you try to pass a string to age it will give you an error, and it will also warn you if you didn't pass one of those required properties. If you want to make them optional, you can add question marks:

// @ts-check

/** @type {import("react").VFC<{ name?: string; age?: number }>} */
export const Example = ({ name, age }) => (
    <h3>
        {name} will be {age + 3} years old in 3 years!
    </h3>
);
Enter fullscreen mode Exit fullscreen mode

Also, you can achieve the same using TS instead of JS with JSDocs, like this:

import type { VFC } from "react";

export const Example: VFC<{ name?: string; age?: number }> = ({
    name,
    age
}) => (
    <h3>
        {name} will be {age + 3} years old in 3 years!
    </h3>
);
Enter fullscreen mode Exit fullscreen mode

The good thing about this approach is that:

  1. You'll get errors in dev, instead of having to reach that component to discover that something is wrong with it in production.
  2. You'll get a better experience in your editor.
  3. You don't need a new runtime dependency (better for the user and for you).

Cheers!

Collapse
aidanmargo profile image
AidanMargo Author

Thanks for this in depth explanation! I learned something this! Great stuff.

Collapse
sergeylukin profile image
Sergey Lukin

you nailed it!