2 ms·
You can extract a type from a typeguard using a conditional type! type TypeOf<T> = (x: any) => x is (infer U) ? U : never; I wrote a really small and simple
by jakelazaroff 7y ago
You can extract a type from a typeguard using a conditional type!
type TypeOf<T> = (x: any) => x is (infer U) ? U : never;
I wrote a really small and simple validator library called narrows that works this way [1]. You could simplify your code like so:
import { number, optional, record, string, TypeOf } from 'narrows';
const isContactInfo = record({
address_1: string,
address_2: optional(string),
city: string,
state: string,
zip: string,
phone: number
})
type ContactInfo = TypeOf<typeof isContactInfo>;
The source is less than 50 lines and super readable if you want to dig in. The libraries in the sibling comments are great too!
[1] https://www.npmjs.com/package/narrows https://www.npmjs.com/package/narrows
- joshAg 7y agoI've been hesitant to switch to something that demands custom type declarations, because we're already autogenerating a lot of types/interfaces with express-openapi (we lean heavily on their request and response validators, too but those don't cover all the types we make), and getting that to play nicely with custom declarations is not my idea of fun. But for the types that aren't tied back to an json-endpoint (we have a few endpoints where we're getting xml or csv or xlsx and a few db<-->backend only interfaces), this looks like a great solution. Typescript-is looks like it might have an overall edge, though, because we can use it on the autogenerated types as well with almost no hassle.