Issue
ref
is a ForwardedRef<HTMLAudioElement>
. So it can either be a function or an object: type ForwardedRef<T> = ((instance: T | null) => void) | MutableRefObject<T | null> | null
I'm checking if ref
is a function in the if block:
const callbackRef = useCallback((node: HTMLAudioElement | null) => {
if (node && typeof ref === 'function') {
ref(node);
} else if (ref) {
node.volume = volume;
ref.current = node;
}
}, [volume]);
Then why is TypeScript still complaining in the else if block?
Property 'current' does not exist on type '((instance: HTMLAudioElement | null) => void) | MutableRefObject<HTMLAudioElement | null>'.
Property 'current' does not exist on type '(instance: HTMLAudioElement | null) => void'.ts(2339)
any
Note: I could do (ref as MutableRefObject<HTMLAudioElement>).current
, but then why would I even bother checking if ref
is a function?
Solution
As I said in the comment: Typescript does not narrow down the type, because you are also checking value of node on the same line, so if node is falsey it never reaches the function check. In the first place I imagine that you don't want the function to reach second if statement anyway if node is falsey, since you will not be able to assign volume to it. As such I recommend just aborting early in such a case, which will resolve your issues.
const callbackRef = useCallback((node: HTMLAudioElement | null) => {
if (!node) return;
if (typeof ref === 'function') {
ref(node);
} else if (ref) {
node.volume = volume;
ref.current = node;
}
}, [volume]);
Answered By - Krzysztof Krzeszewski
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.