'How to infer generic value from return type of an optional prop function?

I have a hook that looks like this:

interface OwnProps<T, F> {
  // ...
  defaultValues: T;
  formatValues?: (values: T) => F;
}

const useValues = <T, F>({ defaultValues, formatValues }: OwnProps<T, F>) => {
  const [values, setValues] = useState(defaultValues);
  
  // change values based on other props and internal processes...

  const formattedValues = useMemo(() => {
    if (!formatValues) return null;

    return formatValues(values);
  }, [values]);

  return { values, formattedValues };
}

I would like for formattedValues to be of type F if the formatValues is provided and null otherwise.

However, even when formatValues is provided, TypeScript still types formattedValues as F | null, since it doesn't know that F is supposed to be binded to the value of formatValues.

Is there a way to make TypeScript recognize that so, when I pass formatValues as a prop, it automatically understands formattedValues will always be of type F?

demo

EDIT

Demo trying to apply @kellys solution using const, but it says:

Type 'F | null' is not assignable to type 'F'.

'F' could be instantiated with an arbitrary type which could be unrelated to 'F | null'.ts



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source