Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

ts-serde

Package Overview
Dependencies
Maintainers
1
Versions
15
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

ts-serde

🎶 Typed Serialization and Deserialization

  • 1.0.2
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
5.1K
decreased by-68.09%
Maintainers
1
Weekly downloads
 
Created
Source

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'
Typeserializedeserialize
stringStringString
numberStringNumber
bigintStringBigInt
booleanStringx === 'true'
integerStringparseInt

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

Keywords

FAQs

Package last updated on 19 Dec 2023

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc