1

I'm trying to strictly type a hook's return callback.

  • If InputType wasn't specified, no input is required when function is called and should complain if any input was provided.
  • If an InputType was specified, it should expect that input type and complain if its not the specified type.

Example

 // overload attempts
 async function someFnAsyncCB(): void;
 async function someFnAsyncCB<InputType>(input: InputType): void;

function useSomeFnHook<InputType = undefined>() {
 const [reactiveVar, setReactiveVar] = useState("");
 // ...
 const someFnAsync = useCallback(
  async function someFnAsyncCB<InputType>(input?: InputType): void {
   // ...
  },
  [reactiveVar, etc],
 );
 return someFnAsync;
}

My implementation works except for when someFnAsync is not called with an input yet InputType is specified with some type other than undefined. Typescript should complain that I didn't supply it an input value.

I tried overloading the function but Typescript doesn't associate the new overload function with the original function.

How would I go about achieving my initial goals?

SILENT
  • 3,916
  • 3
  • 38
  • 57

1 Answers1

-1

You are using a generic type when you don't need a generic type.

Replace

async function someFnAsyncCB<InputType>(input: InputType): void;

with

async function someFnAsyncCB(input: InputType): void;

The modified hook will look like this:

function useSomeFnHook<InputType = undefined>() {
 const [reactiveVar, setReactiveVar] = useState("");
 // ...
 const someFnAsync = useCallback(
                              // No <Generic>
  async function someFnAsyncCB(input?: InputType): void {
   // ...
  },
  [reactiveVar, etc],
 );
 return someFnAsync;
}

Documentation about generics: https://www.typescriptlang.org/docs/handbook/2/generics.html

programmerRaj
  • 1,810
  • 2
  • 9
  • 19
  • 1
    I was using generics for `someFnAsyncCB` when I was trying to overload the function. This solution doesn't resolve my issues. – SILENT Sep 01 '21 at 21:13
  • @SILENT Why do you need to overload the function? – programmerRaj Sep 01 '21 at 21:14
  • Because of "My implementation works except for when someFnAsync is not called with an input yet InputType is specified with some type other than undefined. Typescript should complain that I didn't supply it an input value." – SILENT Sep 01 '21 at 21:15