Skip to content

Infer<T>

ts
type Infer<T>: T extends UnsuccessfulParser ? never : T extends Parser<infer R> ? R : T extends Guard<infer R> ? R : never;

Extract the type from a parser or guards

  • In parsers, extract the type in the type parameter.
  • In guards, extract the type in the type predicate.

Type Parameters

Type ParameterDescription
T extends Guard<unknown> | Parser<unknown>— a parser or guard

Examples

ts
type User = Infer<typeof parseUser>
ts
type User = Infer<typeof isUser>

Limitations

Optional unknown properties will be inferred as required. At runtime, the property is optional: only the inferred type has a discrepancy. For most use cases, this is not a problem. If you are adamant on being correct, consider declaring the type instead of inferring it (see the following section). This edge case is a small compromise between ease-of-use and type correctness.