joi icon indicating copy to clipboard operation
joi copied to clipboard

feat(d.ts): Improve value typing for assert function

Open lxcid opened this issue 1 year ago • 2 comments

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

lxcid avatar Aug 07 '22 03:08 lxcid

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 avatar Aug 20 '22 17:08 Marsup

@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.

lxcid avatar Aug 27 '22 03:08 lxcid