Search code examples
typescriptjsdoc

How to add description to returned object props with JSDoc or TypeScript?


I have a TypeScript project and have a custom hook which returns a bunch of variables isMobile | isDesktop | ... and I'd like to add a description to each of these variables so that somewhere in project I could hover over a variable and get a description (type annotation will come from TS). How can I do that or is that possible?

Hook:

export const useDeviceType = ({ between = [0, 0] } = {}) => {
  const theme = useTheme();
  const isMobile = useMediaQuery(theme.breakpoints.between(0, 'tablet'));
  const isDesktop = useMediaQuery(theme.breakpoints.up('desktop'));
  const isScreenWidthBetween = useMediaQuery(theme.breakpoints.between(between[0], between[1]));

  return useMemo(
    () => ({
      isMobile,
      isDesktop,
      isScreenWidthBetween,
    }),
    [isDesktop, isMobile, isScreenWidthBetween],
  );
};

Somewhere in project:

  const { isDesktop, isMobile } = useDeviceType();

  if (isMobile) {
    // do something
  }

Right now when hovering over isMobile I get const isMobile: boolean but I'd like to add a description to isMobile as well so it would look like this:

const isMobile: boolean
description: isMobile — from 0 to 768px

Solution

  • You could create a type and then define your function to return an instance of that type. And at typedefinition you can add the respective comments

    /**
     * your type-description
     */
    type Foo = {
      /** your property-description */
      isMobile: boolean;
      ...
    }
    
    
    export const useDeviceType = ({ between = [0, 0] } = {}) => {
      const theme = useTheme();
      const isMobile = useMediaQuery(theme.breakpoints.between(0, 'tablet'));
      const isDesktop = useMediaQuery(theme.breakpoints.up('desktop'));
      const isScreenWidthBetween = useMediaQuery(theme.breakpoints.between(between[0], between[1]));
    
      return useMemo(
        () => ({
          isMobile,
          isDesktop,
          isScreenWidthBetween,
        } as Foo),
        [isDesktop, isMobile, isScreenWidthBetween],
      );
    };