ostrowr/ts-json-validator

Feature: type guarded method

moltar opened this issue · 2 comments

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?

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

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