What is MutableRefObject in TypeScript?
A MutableRefObject is the type of a ref that is returned from useRef in React.
An empty MutableRefObject will be the type for { current: undefined }.
This means whatever type you pass in will be used to create the final type that is returned. This is how you would use Generic types which you can read more about here.
For example if you pass in the type string, the type would be returned as MutableRefObject<string> which will look like { current: string }
If you are seeing an error message including "MutableRefObject" it probably just means that you haven’t provided the correct type to the useRef hook compared to how you are using your ref.
For example if you have a ref that only accepts null but you are trying to define it as something else then you might see this error:
const exampleRef = useRef<null>(null) // MutableRefObject<null>
exampleRef.current = "test"
// Type '"test"' is not assignable to type 'null'.
'test' is not assignable to type 'null'
However if you then change this to allow strings as well we no longer will get that error:
const exampleRef = useRef<null | string>(null) // MutableRefObject<null | string>
exampleRef.current = "test"
Source: MutableObjectRef
- If an object satisfies the properties of an interface, then it can be used as a member of that type. Remember dog, this is typescript, it's built on javascript - at runtime there's nothing that enforces an obj to be like an Interface (if it has the properties, it's all good).
- Fanciful def.: describe the shape of an existing Javascript codebase to typescript, and, as a result, you get code completions