ts-serde

1.0.6 • Public • Published

ts-serde

npm-version npm-license npm-download-month npm-min-size ci.yml

🎶 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'
Type serialize deserialize
string String String
number String Number
bigint String BigInt
boolean String x === 'true'
integer String parseInt

Enum

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'

Object

The object conversion methods are JSON and devalue.

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

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)

License

MIT

Package Sidebar

Install

npm i ts-serde

Weekly Downloads

53,410

Version

1.0.6

License

MIT

Unpacked Size

10.8 kB

Total Files

41

Last publish

Collaborators

  • jill64