Nuxt3 using typescript with useFetch and transform option

Viewed 84

I'm using useFetch to fetch an array of strings string[] with the transform option to transform it from array to object.

I tried the code below:

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
      })
    }
);

I'm getting this error

Type '([prop1, prop2, prop3]: ReceivedData) => TransformedData' is not assignable to type '(res: ReceivedData) => ReceivedData'.

I pretty sure I'm messing something here, but Typescript is expecting the transform method to return the same data type it receives.

1 Answers

Currently, you could use it like this:

  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,
  })

Honestly speaking, I hope this will be improved in the future.

Related