joi
joi copied to clipboard
feat(d.ts): Improve value typing for assert function
Referencing #2797, I made a similar change that help Joi.assert()
to assert value type accordingly.
It uses a mixture of asserts condition and user defined type guard.
- https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#assertion-functions
- https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards
I don't know if I'm comfortable with this PR. assert
indeed checks that the value is compatible with the schema, but if there's some conversion happening somewhere, you're going to lure typescript into thinking you've got the correct type while you may not. I'm not sure there's a proper way to type assert
at all, maybe typescript users should only use attempt
with its return value.
@Marsup thanks for the review, i feel that at this point it’s the responsibility of the engineer to understand the schema it assert against and the typing should reflect the behavior. for the general case, we actually have to manually type cast which is more error prone though.
To expand, we might have define a scheme this way:
const DataStructureSchema = Joi.object<DataStructure>({ … });
// assert
const data: unknown = { … };
Joi.assert(data, DataStructureSchema);
// data is DataStructure
in current case, Joi.assert become not super useful in typescript and we had to wrap it in a function that do similar.