I'm trying to pass a type to a React hook:
export function useMyHook<T>() {
const ref = useRef<T>(null!)
useEffect(() => {
ref.current.method() // TypeError: Method does not exist on type
}, [])
return ref
}
And use it like this:
// I want to be able to use multiple types here. MyType, ThatType, ThisType, etc..
const useMyHook<MyType>()
The problem is that the methods on each type I want pass are different, but do the same thing. I also don't want to have to include the ref in each component.
I assume I can do something like this and cast the type when I define the ref?
type RefType = 'MyType' | 'ThatType' | 'ThisType'
export function useMyHook(refType:RefType) {}
But not sure if this is the best way. Ideally I'd like to just decide which methods are available on the ref without TypeScript complaining.