typescript-json-decoder icon indicating copy to clipboard operation
typescript-json-decoder copied to clipboard

Higher-order decoder not typing out in recent library versions

Open zoul opened this issue 2 years ago • 2 comments

Hi! I have a custom higher-order decoder that used to type fine in previous versions (1.0.6) and I can‘t get it working with 1.0.11:

async function fetchQuery<T>(
  query: Query, // some description of the stuff I want to fetch from an API endpoint
  decodeResults: DecoderFunction<T> // decoder for stuff inside some envelope
): Promise<T> {
  // this is the envelope I want to decode and extract results from
  const decodeWrapper = record({
    results: decodeResults, // the actual results are decoded by a decoder supplied by the caller
  });
  return await fetch(/* something */)
    .then((response) => response.json()) // turn response into JSON
    .then(decodeWrapper) // decode envelope
    .then((wrapper) => wrapper.results); // throw away the envelope
}

The basic idea here is to decode some payload with an envelope, throw away the envelope and only return the results (decoded by decodeResults). I would hope for the wrapper on the last line to have type { results: T }, but the actual type is:

addQuestionmarksToRecordFields<{
    results: decodeTypeRecur<T>;
}>

What am I doing wrong? Thank you very much!

zoul avatar May 09 '23 07:05 zoul

Hi, thanks for reporting this!

I've written a test case to reproduce your problem and can see that I experience the same thing. You're not actually doing anything wrong, this is a bug! It's being caused by the new optional (questionmarks ?) in records, which have been a source of several bugs now. I'll see if I manage to find a solution, otherwise I will consider removing the entire optional keys feature.

In the meantime I suggest using a previous version of the library that does what you need, otherwise just cast the last line to the type you expect (something like (wrapper as { result: T }).result). Sorry for the inconvenience.

tskj avatar May 09 '23 20:05 tskj

Thank you for the swift reply! 🙏 It’s a pity that the questionmark feature (which I wanted!) is such a source of bugs. Staying on an older library version works well for us in the meantime.

zoul avatar May 15 '23 07:05 zoul