ostrowr / ts-json-validator

Let JSON play nicely with Typescript
MIT License
342 stars 7 forks source link

Feature: type guarded method #27

Closed moltar closed 4 years ago

moltar commented 4 years ago

Would be great to have a method that returns a type guarded object.

Example:

const parser = new TsjsonParser(
  S({
    type: 'object',
    properties: {
      number: S({ type: 'number' }),
    },
  })
);

// the `data` is any, imagine it is arriving from the API
// and we can't guarantee the shape
const data: any = { number: 1 }

const res = parser.guard(data) // new imaginary `guard` method

console.log(res.number) // `res` is now correctly typed

Do you think something like this is possible?

ostrowr commented 4 years ago

This is certainly possible – but I'm not sure how much utility this adds past the validates method?

Right now, you can do something like

const data: any = { number: 1 }

if (!parser.validates(data)) {
    // throw here
}

// data should be correctly typed here
ostrowr commented 4 years ago

Closing this for now, but if you have a use case for guard that validates doesn't cover, let me know and I'd be happy to add it! (Or, even better, open a PR.)