ts-serde
🎶 Typed Serialization and Deserialization
This library is a type-safe serialization/deserialization library inspired by serde.rs
.
It contains the basic abstract types, some primitive functions, and object functions.
Installation
npm i ts-serde
Types
import { Serde } from 'ts-serde'
import { Serialize, Deserialize } from 'ts-serde/types'
type Serialize<T> = (val: T) => string
type Deserialize<T> = (str: string) => T
type Serde<T> = {
serialize: Serialize<T>
deserialize: Deserialize<T>
}
Primitive
Simple implementation using standard constructors.
import { string, number, boolean, bigint } from 'ts-serde/primitive'
Enum
import { enums } from 'ts-serde/object'
const e = enums(['foo', 'bar', 'baz'])
e.serialize('foo')
e.deserialize('foo')
e.deserialize('qux')
const withFallback = enums(['foo', 'bar', 'baz'], 'fallback')
withFallback.deserialize('qux')
Object
The object conversion methods are JSON
and devalue
.
import { json } from 'ts-serde/object'
const j = json(
(x): x is { key: string } =>
)
j.serialize({ key: 'value' })
j.deserialize('')
devalue
supports more types than JSON.
import { devalue } from 'ts-serde/object'
const d = devalue(
(x): x is Set<Date> =>
,
null
)
d.serialize(new Set([new Date()]))
d.deserialize('')
License
MIT