rhys-vdw / ts-auto-guard

Generate type guard functions from TypeScript interfaces
MIT License
497 stars 54 forks source link

Check of optional attribute fails for null value #133

Closed eth4n closed 3 years ago

eth4n commented 3 years ago

Hi,

I was hoping to use this project to auto-generate type guards for my API models (also auto generated from openAPI generate with typescript-axios). Unfortunately, all type checks on models which do contain an optional attribute fail as parsed JSON object shows "null" instead of "undefined" on empty attributes.

Example:

export interface Person { 
  name: string
  age?: number // Optional attribute
}

Create type guard checks for (typeof obj.age === 'undefined' || typeof obj.age === 'number')

Parsed object from axios client renders as { name: 'Joe', age: null } A check with isPerson({ name: 'Joe', age: null }) will fail as null's type is shown as "object" instead of undefined.

Is this a bug in you library or is there a way to add additional null-check for this situation?

Cheers Christoph

P.S.: Keep up this cool project, really like it!

rhys-vdw commented 3 years ago

Thanks @eth4n <3

Pretty sure this is correct behavior. Optional attributes are undefined if not present. Your type definitions are incorrectly describing the objects you're testing and ts-auto-guard would not be ensuring correct typing if it accepted them.

You'll need to define all your types as e.g. number | null. It's very verbose but FWIW I personally find optional object keys to be rarely appropriate.

I'll leave this issue open for a bit more discussion if necessary.

eth4n commented 3 years ago

Thanks @rhys-vdw for the quick answer. Unfortunately I don't like to mess up with generated code (as I would have to continue to manually fix the code after regeneration). I created a fix-function to convert all null values to undefined values prior to checking with the type guards. I think I will roll with this one. Think I won't get the idea about having null and undefined and differentiate between both of them...

rhys-vdw commented 3 years ago

@eth4n ah, actually. Are you using strictNullChecks? If not then maybe the behaviour you're talking about is desirable. At the moment this library just provides strict type checking, which seems like the most common use case. But I'd be open to supporting both if it can be done in a maintainable way. It would probably need a bit of a refactor.

rhys-vdw commented 3 years ago

Closing for inactivity. Likely an issue of not using strictNullChecks.