RJ
RJ2y ago

Infer type from ObjectValidator which forbids extra properties

I ran into an issue today where I was passing in an object to a validated Convex function which had extra fields not specified by the validator for that function. I got a nice runtime error message in the Convex dashboard logs (huzzah!) but TypeScript had no issue with letting me make this mistake. I don't know how easy it would be to do, but it would be nice to have the inferred TS types of a validator forbid extra properties (like what this utility function does: https://github.com/sindresorhus/type-fest/blob/main/source/exact.d.ts), so that this could be a compilation error rather than a runtime error.
2 Replies
Michal Srb
Michal Srb2y ago
Hey RJ, this is a limitation of TypeScript. Note in the code you linked:
This is useful for function type-guarding to reject arguments with excess properties. Due to the nature of TypeScript, it does not complain if excess properties are provided unless the provided value is an object literal.
Please upvote this issue if you want to have this type as a built-in in TypeScript.
So even with a type helper like that you might run into this surprising behavior - at the cost of a very complicated type signature, which might impact signatures in IDEs and error reporting. It's definitely a problem we're aware of, and might prototype some solution in the future. Thanks for the feedback!
GitHub
Exact Types · Issue #12936 · microsoft/TypeScript
This is a proposal to enable a syntax for exact types. A similar feature can be seen in Flow (https://flowtype.org/docs/objects.html#exact-object-types), but I would like to propose it as a feature...
RJ
RJOP2y ago
Ahh oops, I wasn't aware, thanks for the info!

Did you find this page helpful?