Skip to content

Instantly share code, notes, and snippets.

@krfong916
Last active November 4, 2021 19:35
Show Gist options
  • Save krfong916/a2f6814cc6e4bf68b19a5f5527e18594 to your computer and use it in GitHub Desktop.
Save krfong916/a2f6814cc6e4bf68b19a5f5527e18594 to your computer and use it in GitHub Desktop.

Hot Typescript

Type Narrowing and OR operator

Destructuring Object Parameters

MutableObjectRef

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

Objects and Interfaces

  • 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).

What is a definition file, what's it used for? *.d.ts

  • Fanciful def.: describe the shape of an existing Javascript codebase to typescript, and, as a result, you get code completions
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment