Simple type-safe access to JSON for Typescript
JsonAccess — simple type-safe access to JSON for Typescript
Receiving some string text from an API which is supposedly JSON with
a given structure, we want to parse the JSON and if this does not
fail, access the resulting structured data in a typesafe manner.
Consider an API which is expected to deliver a tuple with type:
[string, number]
and we want to savely access the values to create an Item:
const data = jsonParse(text);
type Item = { id: string; price: number };
const item: Maybe<Item> = jsonAsType(
data,
[jsonStringGetter('item'), jsonNumberGetter('price')],
(i, p) => ({ item: i, price: p })
);
if (!isValid(item)) {
throw item; // a JsonAccessError
}
// continue with item properly typed as Item
For more information see the api documentation.
Setup
To install the package, follow the instruction on codeberg's package page.
Alternatives
TypeScript-first schema validation with static type inference: zod