Building structured data for search engines just got a lot safer. @antinna/schema-ld-types is a comprehensive, type-safe library for Schema.org JSON-LD objects.
Whether you are injecting dynamic SEO metadata or serializing search data, this package ensures both runtime and compile-time accuracy for your structured data pipelines.
✨ Core Features
- Full Type-Safety: Autogenerated TypeScript definitions compiled directly from the official Schema.org vocabulary.
- Validation & Typeguards: Built-in helper utilities to validate and assert schema structures safely at runtime.
- Smart Hydration: Automatically insert missing
@typeproperties onto deeply nested objects based on Schema.org rules. - Serialization / Deserialization: Seamless translation to and from JSON-LD strings, with automatically resolved
@contextwrappers.
📦 Installation
Add the package to your project using npm:
npm install @antinna/schema-ld-types
🚀 Usage Examples
Here are the standard patterns to validate, serialize, deserialize, and type-check your Schema.org JSON-LD elements.
1. Import Types & Utilities
import {
Person,
validate,
assertType,
serialize,
deserialize,
hydrate
} from '@antinna/schema-ld-types';
2. Validate Data (Type Guarding)
Ensure at runtime that an arbitrary object correctly conforms to the expected Schema.org hierarchy.
const data: any = {
'@type': 'Person',
name: 'Jane Doe',
jobTitle: 'Software Engineer',
worksFor: {
'@type': 'Organization',
name: 'Antinna'
}
};
if (validate<Person>(data, 'Person')) {
// TypeScript now knows 'data' is strictly a Person object
console.log(`Successfully verified Person: ${data.name}`);
} else {
console.error("Invalid Person structure!");
}
3. Assertion Testing
Quickly throw an error if an object fails to match the required schema type.
try {
const verifiedPerson = assertType<Person>(data, 'Person');
console.log(verifiedPerson.name);
} catch (error) {
console.error(error.message);
}
4. Serialize to JSON-LD String
Automatically prepend the correct @context and compile your data into a ready-to-inject string.
const author: Person = {
'@type': 'Person',
name: 'Manish',
url: 'https://github.com/manishmg3994'
};
const jsonLdString = serialize(author);
console.log(jsonLdString);
/*
Output:
{
"@context": "https://schema.org",
"@type": "Person",
"name": "Manish",
"url": "https://github.com/manishmg3994"
}
*/
5. Deserialize & Hydrate
Parse a raw JSON-LD string and automatically hydrate missing nested @type properties recursively based on the official schema rules.
const rawJson = `
{
"name": "John Doe",
"worksFor": {
"name": "Antinna"
}
}
`;
// Deserializes and automatically infers worksFor's @type as Organization
const loadedPerson = deserialize<Person>(rawJson, 'Person');
console.log(loadedPerson['@type']); // "Person"
console.log(loadedPerson.worksFor['@type']); // "Organization"
📄 License
This project is open-source and licensed under the MIT License.

Comments
Post a Comment