How to infer the type from `useAsyncData`?

I am getting a list of products through api endpoint. Using useAsyncData it knows what it will be returning, which is great! However, I want to know which product is currently being viewed/selected and I want to give that ref a type that is infered from this data.
const selectedProduct = shallowRef<typeof products.value>()
const { data: products } = await useAsyncData('products', () =>
$fetch('/api/products'),
)
const selectedProduct = shallowRef<typeof products.value>()
const { data: products } = await useAsyncData('products', () =>
$fetch('/api/products'),
)
Here's the thing tho, I want to make that type a single item, not an array of items. But I have no ideas how to unwrap this infered type from Simplify and SerializeObject.
const selectedProduct: ShallowRef<Simplify<SerializeObject<{
id: number;
price: number;
checkoutId: string | undefined;
recurrence: string;
label: string;
description: string;
}>[] | undefined> | null>
const selectedProduct: ShallowRef<Simplify<SerializeObject<{
id: number;
price: number;
checkoutId: string | undefined;
recurrence: string;
label: string;
description: string;
}>[] | undefined> | null>
Help is greatly appreciated!
5 Replies
pyplacca
pyplacca8mo ago
typeof products.value[0]?
Nenad Novakovic
Nenad NovakovicOP8mo ago
Tried [number] and tried [0] and then Type error comes up:
Property '0' does not exist on type 'Simplify<SerializeObject<{ id: number; price: number; checkoutId: string | undefined; recurrence: string; label: string; description: string; }>[] | undefined> | null'.
Property '0' does not exist on type 'Simplify<SerializeObject<{ id: number; price: number; checkoutId: string | undefined; recurrence: string; label: string; description: string; }>[] | undefined> | null'.
Fabian B.
Fabian B.8mo ago
You have to also wrap it in a NonNullable<> before you try to access the array with [number] So NonNullable<typeof products.value>[number] should work in your case This is because you cannot select an array item if the possible value is something like [...] | null | undefined
Nenad Novakovic
Nenad NovakovicOP8mo ago
Would you look at that. Completely forgot about NonNullable last night. Thanks a lot @Fabian B.
Fabian B.
Fabian B.8mo ago
Happy to help 🙂
Want results from more Discord servers?
Add your server