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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@fgv/ts-json-base

v5.0.1

Published

Typescript types and basic functions for working with json

Readme

Summary

Assorted JSON-related typescript utilities that I'm tired of copying from project to project.


Installation

With npm:

npm install ts-json

Overview

Type-Safe JSON

A handful of types express valid JSON as typescript types:

type JsonPrimitive = boolean | number | string | null;
interface JsonObject { [key: string]: JsonValue }
type JsonValue = JsonPrimitive | JsonObject | JsonArray;
interface JsonArray extends Array<JsonValue> { }

JsonCompatible Type

The JsonCompatibleType<T> type provides compile-time validation that a type is JSON-serializable, unlike JsonValue which requires an index signature. This is particularly useful for strongly-typed interfaces.

Basic Usage

import { JsonCompatible } from '@fgv/ts-json-base';

// ✅ JSON-compatible interface
interface UserData {
  id: string;
  name: string;
  preferences: {
    theme: 'light' | 'dark';
    notifications: boolean;
  };
}

// ✅ This type remains unchanged because it's fully JSON-compatible
type ValidatedUserData = JsonCompatibleType<UserData>;

// ❌ Interface with non-JSON properties
interface UserWithMethods {
  id: string;
  name: string;
  save(): Promise<void>;  // Functions are not JSON-serializable
}

// ❌ This type transforms 'save' to an error type
type InvalidUserData = JsonCompatibleType<UserWithMethods>;
// Result: { id: string; name: string; save: ['Error: Function is not JSON-compatible'] }

The MapOf Pattern

The most powerful application is using JsonCompatibleType<T> as a constraint with default type parameters:

class MapOf<T, TV extends JsonCompatibleType<T> = JsonCompatibleType<T>> extends Map<string, TV> {
  public override set(key: string, value: TV): this {
    return super.set(key, value);
  }
}

// ✅ Works perfectly with JSON-compatible types
const userMap = new MapOf<UserData>();
userMap.set('user1', {
  id: 'user1',
  name: 'Alice',
  preferences: { theme: 'dark', notifications: true }
});

// ❌ Prevents usage with non-JSON-compatible types
const badMap = new MapOf<UserWithMethods>();
// The 'save' method becomes type 'never', making the interface unusable

Real-World Examples

API Response Caching:

interface ApiResponse {
  id: string;
  data: unknown;
  timestamp: number;
  metadata: Record<string, string | number>;
}

class ApiCache extends MapOf<ApiResponse> {
  setWithTTL(key: string, response: ApiResponse, ttlMs: number) {
    this.set(key, response);
    setTimeout(() => this.delete(key), ttlMs);
  }
}

Configuration Management:

interface AppConfig {
  features: Record<string, boolean>;
  limits: {
    maxUsers: number;
    maxStorage: number;
  };
  ui: {
    theme: 'light' | 'dark';
    language: string;
  };
}

// Ensures config is always serializable for storage/transmission
const configStore = new MapOf<AppConfig>();

Data Transfer Objects:

// ✅ Perfect for DTOs - no methods, just data
interface CreateUserRequest {
  name: string;
  email: string;
  preferences?: {
    newsletter: boolean;
    theme: string;
  };
}

const requestCache = new MapOf<CreateUserRequest>();

// ❌ Domain objects with behavior are rejected
interface User extends CreateUserRequest {
  id: string;
  save(): Promise<void>;
  validate(): boolean;
}

// This won't work - methods become 'never'
// const userStore = new MapOf<User>();

Array and Nested Validation

// ✅ Arrays of JSON-compatible types work fine
interface DataStructure {
  numbers: number[];
  objects: Array<{ id: number; name: string }>;
  matrix: number[][];
}

const dataMap = new MapOf<DataStructure>();

// ❌ Arrays with functions are detected
interface WithHandlers {
  callbacks: Array<() => void>;  // Functions in arrays also become 'never'
  data: string[];
}

// The 'callbacks' property becomes Array<['Error: Function is not JSON-compatible']>
const handlersMap = new MapOf<WithHandlers>();

Benefits

  1. Compile-time safety: Non-serializable types are caught during development
  2. Clear interfaces: Makes it obvious which types are meant for serialization
  3. Architecture enforcement: Separates data objects from behavior objects
  4. Runtime protection: Prevents serialization errors in production
  5. IDE support: Full autocomplete and error highlighting