1

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()

3 Answers 3

2

We can define a type by combining multiple types like this to achieve required

type Stuff = { first: () => string } & (() => string);

const stuff: Stuff = useCallback(() => {
...    
})();

  stuff.first();

  stuff();
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

useCallback need an array of dependency as the 2nd argument then it can be self infer

import { useCallback } from "react";

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

    major.first = first;

    return major;
  }, []);

  return (
  ...
  );
}

Working Example:

Edit summer-night-zx2bm

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.