Effect CommunityEC
Effect Community2y ago
12 replies
Victor Korzunin

Struggling with Type Inference in TypeScript Hook Function

Hello, dear Typescript experts:
can you please advice
Here is a function declaration:
type HookProps<TData, TVariables, MT extends MutationTuple<TData, TVariables>> = {
  variables: TVariables;
  mutationTuple: MT;
};

declare function useAHook<
  TData,
  TVariables,
  MT extends MutationTuple<TData, TVariables> = MutationTuple<TData, TVariables>
>(props: HookProps<TData, TVariables, MT>): readonly [() => Promise<void>, TData];


I'm struggling to understand what would be my generic declaration to make it correctly infer from function arguments like this:
useAHook({
  variables: {input},
  mutationTuple,
}); // this doesn't work

I have to define types explicitly to make it work:
useAHook<CreateAMutation, Exact<{input: CreateAInput}>>({
  variables: {input},
  mutationTuple,
});


if I do not specify generic types, typescripts infers following:
function useAHook<unknown, {
    input: CreateAInput;
}, MutationTuple<unknown, {
    input: CreateAInput;
}>>(props: HookProps<unknown, {
    input: CreateAInput;
}, MutationTuple<...>>): readonly [() => Promise<void>, unknown]


any ideas?
Was this page helpful?