Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

TypeScript: fieldsAuto + generics = cryptic type error #24

Closed
SimonAlling opened this issue Mar 23, 2023 · 2 comments · Fixed by #34
Closed

TypeScript: fieldsAuto + generics = cryptic type error #24

SimonAlling opened this issue Mar 23, 2023 · 2 comments · Fixed by #34

Comments

@SimonAlling
Copy link
Contributor

This works as expected at run time:

function recordContaining<T>(decodeT: Decoder<T>) {
  const recordDecoder: Decoder<{ foo: T }> = fieldsAuto({ foo: decodeT })
  return recordDecoder
}

recordContaining(boolean)({ foo: false })

But it doesn't type check:

error TS2322: Type 'Decoder<Expand<{ [P in undefined extends T ? "foo" : never]?: { foo: T; }[P]; } & { [P in undefined extends T ? never : "foo"]: { foo: T; }[P]; }>, unknown>' is not assignable to type 'Decoder<{ foo: T; }, unknown>'.
  Type 'Expand<{ [P in undefined extends T ? "foo" : never]?: { foo: T; }[P]; } & { [P in undefined extends T ? never : "foo"]: { foo: T; }[P]; }>' is not assignable to type '{ foo: T; }'.
    Property 'foo' is missing in type '{}' but required in type '{ foo: T; }'.

2   const recordDecoder: Decoder<{ foo: T }> = fieldsAuto({ foo: decodeT });
          ~~~~~~~~~~~~~

The type {} seems suspicious. Perhaps interestingly, the following change doesn't affect the last line of the error message at all:

-  const recordDecoder: Decoder<{ foo: T }> = fieldsAuto({ foo: decodeT })
+  const recordDecoder: Decoder<{ foo: T }> = fieldsAuto({ foo: decodeT, bar: number })

I'm on TypeScript 4.9.5.

@lydell
Copy link
Owner

lydell commented Mar 23, 2023

Yes, fieldsAuto + generics is broken. It’s due to WithUndefinedAsOptional, which is fundamentally broken. (We talked about this elsewhere once if you remember, when someone else reported a similar problem.)

I’ve solved this design mistake, and #22, in the codec branch. You probably won’t be able to see anything interesting in that diff, though, because it’s heavy WIP and features a new (but similar) API (with “codecs” instead of decoders).

The status of the branch is that I’m satisfied with the new API and have managed to make it work type wise. I now need to update documentation and tests, and fix bugs that the tests will uncover.

@SimonAlling
Copy link
Contributor Author

Woah! That's a blazing-fast reply if ever I saw one – and surprisingly delightful at that! Eagerly awaiting tiny-decoders 8.0.0. 🚀

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants