-
-
Notifications
You must be signed in to change notification settings - Fork 2k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix the useRef typing to include undefined when called without initial value #3056
Conversation
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is awesome! Just checked it out but I didn't get a compile error. Presumably, we need to remove the optional sign (=?
) at this line:
Line 53 in cd8d658
export function useRef<T>(initialValue?: T | null): Ref<T>; |
When that's removed accessing myRef.current.foo
errors as expected.
You are right, this change does not do what it was intended to do. Sorry for not checking this thoroughly myself. In my example snippet from above, the I do wonder why this is different between the Anyway, after playing around with this some more, I have come away more confused than before, but have learned this:
My proposal would be to simplify the typings by keeping the argument optional, removing the override, and removing (or deprecating?) the |
88878fd
to
d0f5758
Compare
I went ahead and updated the PR. |
- when `null` is passed as the initial value, the hook returns a `RefObject` will a nullable `current` property. - when an instance of the type is passed, the return type of the hook will not include `null` or `undefined` - when no argument is passed to the hook, the `current` property of the returned object will include `undefined`. This change also deprecated the `PropRef<T>` type, as it is exactly the same as `Ref<T>`.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Love it, this works and is much better 🙌
+1 on deprecating the PropRef
type
Fix the
PropRef
typing in hooks to include theundefined
type for thecurrent
property, as it will be undefined (at least) on initial render.This was changed in #2803 when the
current
property was made non-optional, but it still needs to include theundefined
type. Thecurrent
property will always beundefined
on initial render, for example:This change made in this PR mirrors the corresponding override in the React typings:
See https://github.com/DefinitelyTyped/DefinitelyTyped/blob/e47aff8a3a1331d0c540550db79dd5065ab735e5/types/react/index.d.ts#L1045