🎶 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.
npm i ts-serde
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>
}
Simple implementation using standard constructors.
import { string, number, boolean, bigint } from 'ts-serde/primitive'
Type | serialize | deserialize |
---|---|---|
string | String |
String |
number | String |
Number |
bigint | String |
BigInt |
boolean | String |
x === 'true' |
integer | String |
parseInt |
import { enums } from 'ts-serde/object'
const e = enums(['foo', 'bar', 'baz'])
e.serialize('foo') // => 'foo'
e.deserialize('foo') // => 'foo'
e.deserialize('qux') // => To Throw Error
const withFallback = enums(['foo', 'bar', 'baz'], 'fallback')
withFallback.deserialize('qux') // => 'fallback'
The object conversion methods are JSON
and devalue
.
To add a type guard inline
import { json } from 'ts-serde/object'
const j = json(
(x): x is { key: string } =>
// ... Type Guard
)
j.serialize({ key: 'value' }) // => '{"key":"value"}'
j.deserialize('') // => To Throw Error
Use type
to add a type guard instead interface
for external type definition
import { json } from 'ts-serde/object'
type Settings = {
v: string;
lwm: {
expanded: boolean
}
}
const j =json<Settings>(
(x): x is Settings =>
// ... Type Guard
)
devalue
supports more types than JSON.
import { devalue } from 'ts-serde/object'
const d = devalue(
(x): x is Set<Date> =>
// ... Type Guard
,
null // fallback value
)
d.serialize(new Set([new Date()]))
// => '[["Set",1],["Date","20XX-01-01T00:00:00.000Z"]]'
d.deserialize('') // => null (fallback value)