Skip to content
Advertisement

Typescript object with default function typing in React

I wonder how this code written in JavaScript

const stuff = useCallback(() => { 
    function first() { 
        return "firstStaff"; 
    }
    function major() { 
        return "majorStaff";
    }
    
    major.first = first;
    
    return major;
})();

Can be written with correct types in TypeScript, so it has the right hints for stuff() and stuff.first()

Advertisement

Answer

If you are interested in function static property typing you can use this example:

import { useCallback } from 'react'

interface Major {
  (): string
  first: () => string
}

const stuff = useCallback((): Major => {
  function first() {
    return "firstStaff";
  }
  function major() {
    return "majorStaff";
  }

  major.first = first;

  return major;
}, [])();

Playground

Please see this question/answer if you want to know more about typing static function properties

Advertisement