polymorphic-serializable
v0.1.4
Published
Type-safe, polymorphic, decorator-driven JSON serialization for TypeScript
Maintainers
Readme
polymorphic-serializable
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-serializable3. 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): Duringinstance.toJSON(), the registered type ID is prepended to the serialized payload under the reserved_typeproperty. - Dual Registry: A global constructor registry maps type IDs to class constructors, while an internal
WeakMapprototype 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 staticdeserialize()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() ?? nulland 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):- Validates that the payload is a non-null, non-array object.
- Validates that
_typeis present and a non-empty string. - Resolves the runtime constructor from the registry.
- Pre-validates
expectedTypeto ensure the registered constructor extends or matches it before callingdeserialize(). - Strips
_typefrom the payload before passing it todeserialize(). - Post-validates that the returned instance is an
instanceofboth the runtime constructor andexpectedType.
- Domain-Level Validation (
deserialize):- Each class's
deserialize()is responsible for validating its own domain properties (fields, primitives, nested objects).
- Each class's
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:
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 { // ... }Use
new this(...)indeserialize(): Recommended for wrapper-compatible polymorphic deserialization. Constructing vianew 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 | nullJsonValue:JsonPrimitive | JsonObject | JsonArrayJsonObject:{ [key: string]: JsonValue }JsonArray:JsonValue[]
Shallow Runtime Validation
Runtime validation performed by Serializable is intentionally shallow:
- The framework validates top-level object structure, reserved
_typeconstraints, 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 anError. - 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.ts15. 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(): JsonObjectDefines serializable domain properties. Must not return_type.public toJSON(): JsonObjectSerializes the instance to a JSON object with its registered_typemetadata tag.public static fromJSON(json: unknown): SerializableDeserializes a payload by resolving its_typetag.public static fromJSON<T extends Serializable>(json: unknown, expectedType: abstract new (...args: any[]) => T): TDeserializes a payload and verifies inheritance againstexpectedType.public static fromJSONOptional<T extends Serializable>(json: unknown, expectedType: abstract new (...args: any[]) => T): T | undefinedDeserializes an optional payload, returningundefinedifjsonisnullorundefined, or delegating tofromJSON()otherwise.public static register<T extends SerializableConstructor>(typeId: string, options?: SerializableRegistrationOptions): (constructor: T, context: ClassDecoratorContext<T>) => voidDecorator registration factory.public static register<T extends SerializableConstructor>(typeId: string, constructor: T, options?: SerializableRegistrationOptions): voidImperative registration function.
Types & Options
SerializationContractMode:'own' | 'inherited'SerializableRegistrationOptions:{ contract?: SerializationContractMode }SerializableConstructor<T>: Interface for serializable constructors withstatic 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:examples18. License
MIT
