npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

polymorphic-serializable

v0.1.4

Published

Type-safe, polymorphic, decorator-driven JSON serialization for TypeScript

Readme

polymorphic-serializable

CI codecov Quality gate status Coverage Duplicated Lines (%) Reliability Rating Security Rating License: MIT


1. Serializable

Serializable is a TypeScript serialization base class.

  • Lightweight
  • Zero-dependency
  • Polymorphic
  • Enables round-trip JSON serialization and deserialization

2. Installation

npm install polymorphic-serializable

3. Requirements

  • JavaScript Target: ES2022 or newer (relies on Object.hasOwn()).
  • TypeScript: 5.0 or newer for modern ECMAScript standard decorators (ClassDecoratorContext, context.addInitializer()).
  • Legacy Decorators: The package does not provide legacy experimental decorator polyfills. Projects using TypeScript legacy decorators (experimentalDecorators: true) must use imperative registration instead: Serializable.register('type-id', Class).

4. Quick Start

import {
    Serializable,
    type JsonObject
} from 'polymorphic-serializable';

@Serializable.register('user-profile')
class UserProfile extends Serializable {
    public constructor(
        public readonly username: string,
        public readonly email: string
    ) {
        super();
    }

    protected serialize(): JsonObject {
        return {
            username: this.username,
            email: this.email
        };
    }

    public static deserialize(json: JsonObject): UserProfile {
        return new this(
            json['username'] as string,
            json['email'] as string
        );
    }
}

// 1. Serialization
const user = new UserProfile('alice', '[email protected]');
const json = user.toJSON();
// Output: { _type: 'user-profile', username: 'alice', email: '[email protected]' }

// 2. Deserialization with expected type
const restored = Serializable.fromJSON(json, UserProfile);
console.log(restored instanceof UserProfile); // true
console.log(restored.username); // 'alice'

5. How It Works

  • Stable Type IDs: Classes are registered under explicit, unique string IDs rather than constructor names, guaranteeing stability across code minification and bundler transformations.
  • Metadata Tag (_type): During instance.toJSON(), the registered type ID is prepended to the serialized payload under the reserved _type property.
  • Dual Registry: A global constructor registry maps type IDs to class constructors, while an internal WeakMap prototype registry maps exact runtime prototypes to their type IDs.
  • Round-Trip Deserialization: Serializable.fromJSON(json, ExpectedType) verifies payload structure, strips _type, resolves the constructor, validates hierarchy, and invokes the class's static deserialize() method.

6. Registration

Serializable classes can be registered either via decorators or imperatively.

Decorator Registration

Modern ECMAScript standard class decorator syntax:

@Serializable.register('user-profile')
class UserProfile extends Serializable {
    // ...
}

Imperative Registration

Direct registration without decorators, ideal for environments without decorator support or legacy configurations:

class Order extends Serializable {
    // ...
}

Serializable.register('customer-order', Order);

contract: 'own' (Default)

By default, the registered class must directly declare its own serialize() method on its prototype and its own static deserialize() method on the constructor. This prevents accidental inheritance of incompatible serialization methods.

@Serializable.register('custom-item', { contract: 'own' })
class CustomItem extends Serializable {
    protected serialize(): JsonObject { return {}; }
    public static deserialize(json: JsonObject): CustomItem { return new this(); }
}

contract: 'inherited'

Allows a subclass to intentionally reuse inherited serialize() and/or deserialize() implementations from its superclass:

@Serializable.register('special-user', { contract: 'inherited' })
class SpecialUser extends UserProfile {
    // Reuses UserProfile.prototype.serialize and UserProfile.deserialize
}

7. Nested Serializable Objects

Nested Serializable objects should serialize using child.toJSON() and deserialize using Serializable.fromJSON():

protected serialize(): JsonObject {
    return {
        name: this.name,
        address: this.address.toJSON()
    };
}

public static deserialize(json: JsonObject): UserAccount {
    const address = Serializable.fromJSON(json['address'], Address);
    return new this(json['name'] as string, address);
}

Optional Nested Properties

For optional nested properties (address?: Address), serialize them cleanly using optional chaining and null coalescing:

address: this.address?.toJSON() ?? null

and deserialize them using Serializable.fromJSONOptional():

const address = Serializable.fromJSONOptional(
    json['address'],
    Address
);

Serializable.fromJSONOptional() treats both null and undefined as "not present" (returning undefined). Any other value passes through to Serializable.fromJSON() for standard validation and type checking.

See executable example: examples/02-nested-serializable.ts.


8. Recursive Structures

Recursive tree structures (e.g., nodes containing arrays of child nodes) are fully supported. Because Serializable.fromJSON() accepts json: unknown, mapping child arrays is concise and does not require type assertions:

const children = rawChildren.map(child =>
    Serializable.fromJSON(child, TreeNode)
);
  • Trees Supported: Multi-level hierarchical trees serialize and deserialize cleanly.
  • Cyclic Graphs Not Supported: Cyclic object graphs (where nodes reference ancestors or create cycles) are not currently supported because JSON cannot represent circular structures natively.

See executable example: examples/03-recursive-tree.ts.


9. Deserialization & Type Checking

Serializable.fromJSON() accepts input typed as unknown and acts as the runtime validation boundary.

Validation Responsibilities

  • Framework-Level Validation (fromJSON):
    1. Validates that the payload is a non-null, non-array object.
    2. Validates that _type is present and a non-empty string.
    3. Resolves the runtime constructor from the registry.
    4. Pre-validates expectedType to ensure the registered constructor extends or matches it before calling deserialize().
    5. Strips _type from the payload before passing it to deserialize().
    6. Post-validates that the returned instance is an instanceof both the runtime constructor and expectedType.
  • Domain-Level Validation (deserialize):
    • Each class's deserialize() is responsible for validating its own domain properties (fields, primitives, nested objects).

Usage Signatures

// Strongly-typed deserialization:
const user: UserProfile = Serializable.fromJSON(payload, UserProfile);

// Untyped deserialization (returns Serializable instance):
const item: Serializable = Serializable.fromJSON(payload);

10. Decorators and Runtime Wrappers

When combining @Serializable.register() with other class decorators:

  1. Place @Serializable.register() closest to the class: Innermost / at the bottom of the decorator list. This ensures the base class contract is validated during decoration, and the outer runtime wrapper is registered when class initializers run.

    @AuditLog()
    @Serializable.register('audit-item')
    class AuditItem extends Serializable {
        // ...
    }
  2. Use new this(...) in deserialize(): Recommended for wrapper-compatible polymorphic deserialization. Constructing via new this(...) ensures the returned instance matches the final runtime wrapper subclass rather than a hardcoded base constructor.

See executable example: examples/06-decorator-wrapper.ts.


11. JSON Types & Validation

The package exports recursive JSON types for TypeScript consumers:

  • JsonPrimitive: string | number | boolean | null
  • JsonValue: JsonPrimitive | JsonObject | JsonArray
  • JsonObject: { [key: string]: JsonValue }
  • JsonArray: JsonValue[]

Shallow Runtime Validation

Runtime validation performed by Serializable is intentionally shallow:

  • The framework validates top-level object structure, reserved _type constraints, and constructor identities.
  • Deep recursive validation of nested primitives is intentionally omitted for performance. Serializers must ensure data is JSON-compatible (finite numbers, no BigInt, no functions).

12. Exact Runtime Types

Registration attaches strictly to the exact runtime prototype (Object.getPrototypeOf(instance)):

  • No Automatic Subclass Inheritance: Unregistered subclasses do not automatically inherit a parent's serialization identity. Calling toJSON() on an instance of an unregistered subclass throws an Error.
  • Explicit Opt-in: Every concrete subclass that should be serializable must be registered explicitly, either with its own contract or with { contract: 'inherited' }.

See executable example: examples/04-inheritance.ts.


13. Errors

The framework produces clear, explicit errors:

| Error Type | Condition | | :--- | :--- | | TypeError | Non-object, null, or array payload passed to fromJSON(). | | TypeError | Missing, empty, or non-string _type property. | | TypeError | serialize() returns a non-object, an array, or an object with reserved _type. | | TypeError | Class does not extend Serializable or fails contract validation. | | TypeError | Deserialized instance does not match expectedType or runtime constructor. | | Error | Deserializing an unknown type ID. | | Error | Serializing an unregistered class instance ("Class \"...\" is not registered for serialization..." or fallback "This object is not registered for serialization..."). | | Error | Duplicate registration of an existing type ID or runtime prototype. |


14. Examples

Runnable examples are located in the examples/ directory:

| Example | Description | | :--- | :--- | | 01-basic.ts | Register a basic Serializable class and serialize/deserialize it to JSON. | | 02-nested-serializable.ts | Nested Serializable properties, required and optional. | | 03-recursive-tree.ts | Recursive Serializable structures. | | 04-inheritance.ts | Subclassing and inherited serialization contracts. | | 05-imperative-registration.ts | Registering classes imperatively, a decorator-free alternative. | | 06-decorator-wrapper.ts | Combining with advanced decorators. |

Run any example using ts-node:

npx ts-node examples/01-basic.ts

15. Limitations / Non-goals

  • Cyclic Graphs: Cyclic object graphs are not supported.
  • Deep Runtime Schema Validation: Deep primitive validation is not performed at runtime; use static typing or domain schema libraries (e.g. Zod) in deserialize() if needed.
  • Implicit Subclass Inheritance: Subclasses must be registered explicitly; type IDs are never inferred from parents.
  • Legacy Decorator Emulation: TypeScript experimental decorators (stage 1/2) are not emulated; use imperative registration instead.

16. API Reference

Serializable (Abstract Base Class)

  • protected abstract serialize(): JsonObject Defines serializable domain properties. Must not return _type.
  • public toJSON(): JsonObject Serializes the instance to a JSON object with its registered _type metadata tag.
  • public static fromJSON(json: unknown): Serializable Deserializes a payload by resolving its _type tag.
  • public static fromJSON<T extends Serializable>(json: unknown, expectedType: abstract new (...args: any[]) => T): T Deserializes a payload and verifies inheritance against expectedType.
  • public static fromJSONOptional<T extends Serializable>(json: unknown, expectedType: abstract new (...args: any[]) => T): T | undefined Deserializes an optional payload, returning undefined if json is null or undefined, or delegating to fromJSON() otherwise.
  • public static register<T extends SerializableConstructor>(typeId: string, options?: SerializableRegistrationOptions): (constructor: T, context: ClassDecoratorContext<T>) => void Decorator registration factory.
  • public static register<T extends SerializableConstructor>(typeId: string, constructor: T, options?: SerializableRegistrationOptions): void Imperative registration function.

Types & Options

  • SerializationContractMode: 'own' | 'inherited'
  • SerializableRegistrationOptions: { contract?: SerializationContractMode }
  • SerializableConstructor<T>: Interface for serializable constructors with static deserialize(json: JsonObject): T.
  • JsonPrimitive, JsonValue, JsonObject, JsonArray: Recursive JSON types.

17. Development

# Install dependencies
npm install

# Run unit tests and coverage
npm test

# Build package
npm run build

# Typecheck and compile examples
npm run build:examples

18. License

MIT