https://github.com/ascandone/ts-decode
Straightforward, type-safe `unknown => T` decoding combinators
https://github.com/ascandone/ts-decode
decoding json typesafe typescript validation
Last synced: 3 months ago
JSON representation
Straightforward, type-safe `unknown => T` decoding combinators
- Host: GitHub
- URL: https://github.com/ascandone/ts-decode
- Owner: ascandone
- Created: 2021-12-02T09:57:34.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2024-02-08T21:38:16.000Z (over 2 years ago)
- Last Synced: 2025-10-06T14:54:49.399Z (9 months ago)
- Topics: decoding, json, typesafe, typescript, validation
- Language: TypeScript
- Homepage: https://ts-decode.netlify.app/modules
- Size: 408 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
Awesome Lists containing this project
README
[](https://www.npmjs.com/package/ts-decode)  
  
## `ts-decode`
> Straightforward, type-safe `unknown => T` decoding combinators
### Install
```bash
# using npm
npm i ts-decode
# using yarn
yarn add ts-decode
```
### Usage
```ts
// We can compose the decoders to create new decoders
const personTypeDecoder = oneOf(
hardcoded("developer"),
hardcoded("project manager"),
hardcoded("designer"),
);
const personDecoder = object({
name: string.required,
id: number.required,
kind: personTypeDecoder.required,
phoneNumbers: array(string).optional,
});
/*
Automagically inferred as:
type Person = {
name: string;
id: number;
kind: "developer" | "project manager" | "designer";
phoneNumbers?: string[] | undefined;
}
*/
type Person = Infer;
// The decoder can now validate a value of unknown type
const json = JSON.parse(`
{ "name": "John Doe",
"id": 1234,
"kind": "project-manager",
"phoneNumbers": ["123123123"]
}
`);
const result = personDecoder.decode(json);
if (result.error === false) {
// now we have the compile-time guarantee that this
const person = result.value;
// has type `Person` without manual casting
} else {
// Or if it failed we can log the error description
const reason = result.reason;
console.error(reasonToXmlString(reason));
}
```
By the way, did you notice the bug?
Good thing we printed it out
```xml
Expected "developer", got "project-manager" instead
Expected "project manager", got "project-manager" instead
Expected "designer", got "project-manager" instead
```
You can find the complete typedocs-generated API [here](https://ts-decode.netlify.app/modules.html) or you can try it in a [codesanbox](https://codesandbox.io/s/ts-decode-playground-xw3yb?file=/src/index.ts)