nuxt3.js - Nuxt3 folosind TypeScript cu useFetch și opțiunea transform
Folosesc useFetch pentru a prelua un array de stringuri string[] cu opțiunea transform pentru a-l transforma din array în obiect.
Am încercat codul de mai jos:
type ReceivedData = [string, string, string];
interface TransformedData {
prop1: string,
prop2: string,
prop3: string
}
const { data, error } = await useFetch<ReceivedData>(
`./jsonPath.json`,
{
transform: ([prop1, prop2, prop3]: ReceivedData): TransformedData => ({
prop1, prop2, prop3
})
}
);
Primesc această eroare
Type '([prop1, prop2, prop3]: ReceivedData) => TransformedData' is not assignable to type '(res: ReceivedData) => ReceivedData'.Sunt destul de sigur că greșesc ceva aici, dar TypeScript se așteaptă ca metoda transform să returneze același tip de date pe care îl primește.
Răspuns #1
Am avut aceeași problemă. Ce a funcționat pentru mine a fost să omit tipul generic din apelul useFetch și să atribui tipul așteptat al răspunsului parametrului transform
const { data, error } = await useFetch(
`./jsonPath.json`,
{
transform: ([prop1, prop2, prop3]: ReceivedData): TransformedData => ({
prop1, prop2, prop3
})
}
);
Răspunsul #2
În prezent, ai putea să-l folosești în felul următor:
type ReceivedData = [string, string, string]
interface TransformedData {
prop1: string
prop2: string
prop3: string
}
const transform = ([prop1, prop2, prop3]: ReceivedData): TransformedData => ({
prop1,
prop2,
prop3,
})
const { data } = await useFetch<
ReceivedData,
Error,
string,
ReceivedData,
typeof transform
>(`./jsonPath.json`, {
transform,
})
Sincer să fiu, sper ca acest lucru să fie îmbunătățit în viitor.
