jackocnr / intl-tel-input

A JavaScript plugin for entering and validating international telephone numbers
https://intl-tel-input.com
MIT License
7.36k stars 1.92k forks source link

Fix react `ref` Typescript types #1665

Closed crcarrick closed 2 weeks ago

crcarrick commented 2 weeks ago

Hello 👋

The current React types don't strongly type the forwarded ref object. So, when using the component exported from the intl-tel-input/react or intl-tel-input/reactWithUtils packages with Typescript, you can't actually pass a ref to the component.

import IntlTelInput from 'intl-tel-input/react'

// ❌ Property 'ref' does not exist on type ...
<IntlTelInput 
  ref={/* ... */}
/>

I added a IntlTelInputRef type to the ref object, and exported it. The reason the type itself is exported is so that consumers can type their useRef, for example:

import IntlTelInput from 'intl-tel-input/react'
import type { IntlTelInputRef } from 'intl-tel-input/react'

const ref = useRef<IntlTelInputRef>(null)

// ✅ typechecks 
<IntlTelInput 
  /* ... other props */
  ref={ref}
/>

No actual changes to the functionality of the React components or underlying library were made in this PR. This is solely a Typescript fix.

jackocnr commented 2 weeks ago

Looks great, thank you!

jackocnr commented 2 weeks ago

Released in v23.1.0