AlexGalays / idonttrustlikethat

Validation for TypeScript
40 stars 7 forks source link

`object` validator returns optional properties always #6

Closed bebeto84 closed 3 years ago

bebeto84 commented 3 years ago

Hey, just using your library for quite a while, and thanks! It is awesome. BTW there was a warning I was ignoring since mmmm always (not sure TBH)?

The problem resides in the validation object that converts the object passed as optional properties, not taking in account that some of them (or all) are not optional, so when you try to cast TS to Validator<T> the code below will produce an error: const validatorMyObject: Validator<MyObject> 'validatorMyObject' is declared but its value is never read.ts(6133) Type 'ObjectValidator<{ value: Validator<string>; age: Validator<number>; }>' is not assignable to type 'Validator<MyObject>'. Types of property 'T' are incompatible. Type '{ value?: string; age?: number; }' is not assignable to type 'MyObject'. Property 'value' is optional in type '{ value?: string; age?: number; }' but required in type 'MyObject'.ts(2322)

interface MyObject {
  value: string; 
  age: number;
}

const validatorMyObject: Validator<MyObject> = object({
  value: string;
  age: number;
}):

It seems to me that the MandatoryKeys approach is not working correctly. From my point of view, there shouldn't be any difference between OptionalKeys and MandatoryKeys, since you are already differentiating them with the colon(:), so we already know in this way which is optional and which mandatory.

Could you please take a look @AlexGalays ?

Many thanks!

AlexGalays commented 3 years ago

Hummm curious!

Can you show your tsconfig or equivalent?

bebeto84 commented 3 years ago

Hey, just created a simple Stackblitz project (not changed any default configuration on tsconfig) that reproduces the problem

AlexGalays commented 3 years ago

Thanks for the repro. It's in fact normal; I should perhaps mention in the README that the lib is really meant to be used with strict: true, or more specifically in this case, strictNullChecks: true to beneficiate from this lib typesafety. I really don't think it can be made to work properly otherwise.

Cheers!