profile
viewpoint

Ask questionsGeneric for parsing objects

Really enjoy the library! Thank you for the work!

To easier debug when a parse fails, I made a small wrapper like this:

function parse(parser, obj) {
  try {
    return parser.parse(obj);
  } catch (e) {
    console.log(obj);
    throw e;
  }
}

The problem is that typescript can not infer this function.

I tried multiple combinations but can not seem to get it right.

I looked through issues already mentioning generic and did fine one small example: https://github.com/vriad/zod/issues/93 but it did not help fully.

function parse<K, T extends z.ZodType<K, any>>(parser: T, obj): K {
  try {
    return parser.parse(obj);
  } catch (e) {
    console.log(obj);
    throw e;
  }
}
function parse<T extends z.ZodType<any, any>, K typeof T>(parser: T, obj): K {
  try {
    return parser.parse(obj);
  } catch (e) {
    console.log(obj);
    throw e;
  }
}
interface Schema<T> {
  parse: (data:unknown): T;
  check: (data:unknown): data is T;
}
function parse<T extends Schema<K>>(parser: T, obj) {
  try {
    return parser.parse(obj);
  } catch (e) {
    console.log(obj);
    throw e;
  }
}
interface SchemaVal {
  parse<K>(data: unknown): K;
}

function parse<T extends SchemaVal>(parser: T, obj): K {
  try {
    return parser.parse(obj);
  } catch (e) {
    console.log(obj);
    throw e;
  }
}
vriad/zod

Answer questions chrbala

Yeah, that seems about right for the sync implementation. It does look like params is unused though - not sure if that was intentional.

useful!

Related questions

No questions were found.
source:https://uonfu.com/
Github User Rank List