-
It works fine when using the const App = () => {
const { data, status } = useQuery({
queryKey: ["abc"],
queryFn: () => "hello world"
})
if (status === 'success') {
// data is correctly a `string`
}
} However, if I wrap my const useMe = () => {
const queryResult = useQuery({
queryKey: ["abc"],
queryFn: () => "hello world"
})
return [queryResult, 'John Doe'] as const
}
const App = () => {
const [{ data, status }, name] = useMe()
if (status === 'success') {
// data is still `string | undefined`
}
} But, if I do not destructure the first returned item, the type narrowing is back: const App = () => {
const [queryResult, name] = useMe()
if (queryResult.status === 'success') {
// queryResult.data is now `string`
}
} How do I correctly create my custom hook so that it also works with destructuring assignment like the original |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 5 replies
-
this should work with TypeScript 4.6 and higher: https://devblogs.microsoft.com/typescript/announcing-typescript-4-6/#cfa-destructured-discriminated-unions |
Beta Was this translation helpful? Give feedback.
-
It seems to be a missing feature of TypeScript, that type narrowing doesn't work when destructuring discriminated union within a destructured array. |
Beta Was this translation helpful? Give feedback.
-
I have a similar question but more related to destructuring Let's assume this is my abstraction on top of export function useGet() {
const { data, isError, isPending, isSuccess, error } = useQuery({
queryKey: ["hello"],
queryFn: async () => "Hello World"
});
return {
error,
data,
isError,
isPending,
isSuccess
};
} Then, in my UI component I use that abstraction: const HelloWorld = () => {
const { data, isError, isPending, error } = useGet();
if (isError) return `Oops, something went wrong: ${error}`;
if (isPending) return "Loading...";
return (
<>
{data}
</>
);
}; Because I am destructuring the features from If I expose the whole |
Beta Was this translation helpful? Give feedback.
It seems to be a missing feature of TypeScript, that type narrowing doesn't work when destructuring discriminated union within a destructured array.
microsoft/TypeScript#55664