-
-
Notifications
You must be signed in to change notification settings - Fork 5.3k
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
[TypeScript] Fix useGetOne and useGetMany params type when id param is undefined #9971
Conversation
… false ## Problem TypeScript complains when `useGetOne` is called with an undefined `id`. This is fine, except when using the `enabled` option: ```jsx const { data, error, isPending } = useGetOne<Post>( 'posts', { id: comment?.post_id }, { enabled: !!comment } ); ``` ## Solution Use type overloads to allow optional id when enabled is specified.
Now I wonder if that's the right fix. Instead of forcing users to set the enabled flag when the main param may be undefined, shouldn't we relax the params type to accept undefined values, and set the enabled flag ourselves if the main param is undefined? |
I like this idea 👍 |
describe('TypeScript', () => { | ||
it('should return the parametric type', () => { | ||
type Foo = { id: number; name: string }; | ||
const _Dummy = () => { | ||
const { data, error, isPending } = useGetOne<Foo>('posts', { | ||
id: 1, | ||
}); | ||
if (isPending || error) return null; | ||
return <div>{data.name}</div>; | ||
}; | ||
// no render needed, only checking types | ||
}); | ||
it('should accept empty id param', () => { | ||
const _Dummy = () => { | ||
type Comment = { | ||
id: number; | ||
post_id: number; | ||
}; | ||
const { data: comment } = useGetOne<Comment>('comments', { | ||
id: 1, | ||
}); | ||
type Post = { | ||
id: number; | ||
title: string; | ||
}; | ||
const { data, error, isPending } = useGetOne<Post>('posts', { | ||
id: comment?.post_id, | ||
}); | ||
if (isPending || error) return null; | ||
return <div>{data.title}</div>; | ||
}; | ||
// no render needed, only checking types | ||
}); | ||
}); |
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.
Unfortunately, as we don't compile our tests, we won't ever see this fail in CI
@@ -398,4 +398,45 @@ describe('useGetMany', () => { | |||
expect(abort).toHaveBeenCalled(); | |||
}); | |||
}); | |||
|
|||
describe('TypeScript', () => { |
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.
same
Problem
TypeScript complains when
useGetOne
is called with an undefinedid
. This is fine, except when using theenabled
option:This is a consequence of the strictNullCheck flag in ra-core.
Solutions
We choose solution 2.