I developed a React hook that makes a request to a remote API and returns a value. By default, when the API is fetching, the returned value is set to undefined
.
However, I added a new option that allows for setting a default value - so if the API is still in the process of fetching, the default value will be returned instead.
My question is, can TypeScript automatically deduce that when defaultValue
is provided, then the return type cannot be undefined
?
This is the code I have written so far:
interface UseMyHookOptions<T> {
defaultValue?: T
}
type UseMyHookReturn<T> = T extends undefined
? [T | undefined, (data: T) => void]
: [T, (data: T) => void]
function useMyHook<T>(key: string, options: UseMyHookOptions<T> = {}): UseMyHookReturn<T>{
const defaultValue = options?.defaultValue
const remoteValue = useFetch<T>(`/api/${key}`)
const setValue = (value: T) => { console.log(value) }
const value = remoteValue ?? defaultValue;
return [value, setValue] as UseMyHookReturn<T>;
}
Examples:
// Expected type for `foo`: T (since defaultValue is provided)
// actual type: T
const [foo, setFoo] = useMyHook<string>('foo', { defaultValue: 'something' });
// Expected type for `bar`: T | undefined (since no defaultValue is specified)
// actual type: T
const [bar, setBar] = useMyHook<string>('bar');