JSON-typescript Basic Type Definitions

1.1.2 · abandoned · verified Sun Apr 19

This package provides fundamental TypeScript type definitions specifically for JSON objects. Its primary purpose is to enable compile-time validation of JSON structures, ensuring that data conforms to expected shapes like `JSONValue` or `JSONObject`. The package is currently at version 1.1.2, with its last release in March 2019, indicating an inactive development cadence. Unlike more advanced libraries that generate JSON schemas from TypeScript types (e.g., `json-schema-to-typescript`) or provide runtime object mapping (e.g., `json2typescript`), `json-typescript` focuses solely on offering basic structural types for static analysis. It's suitable for projects needing straightforward type enforcement for incoming or outgoing JSON data at compile time.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates installation and basic usage of JSON-typescript for compile-time validation of JSON structures, highlighting correct and incorrect type assignments.

npm install --save-dev json-typescript

// tsconfig.json might need:
// {
//   "compilerOptions": {
//     "moduleResolution": "node",
//     "esModuleInterop": true
//   }
// }

import type { Value as JSONValue, Object as JSONObject } from 'json-typescript';

// ✅ This should be OK: a valid JSON structure
let validDoc: JSONValue = {
  data: {
    type: 'articles',
    id: '1',
    attributes: {
      title: 'My Article',
      content: 'Hello World!'
    }
  },
  meta: {
    timestamp: new Date().toISOString()
  }
};

// ⛔️ This should NOT be OK (functions are not allowed in JSONValue)
// let invalidDocWithFunction: JSONValue = {
//   foo() { return 'bar'; }
// };

// ⛔️ This should NOT be OK (Array is not a JSONObject, it's a JSONValue)
// let invalidDocAsArray: JSONObject = [];

// Correct usage of JSONObject:
let myJsonObject: JSONObject = {
  key1: 'value1',
  key2: 123,
  key3: true,
  key4: null,
  key5: { nested: 'object' },
  key6: ['array', 456]
};

console.log('Valid JSON Document:', validDoc);
console.log('My JSON Object:', myJsonObject);

view raw JSON →