@antinna/schema-ld-types
v1.0.0
Published
TypeSafe library for Schema.org JSON-LD with validation and serialization.
Readme
@antinna/schema-ld-types
A comprehensive, typesafe library for Schema.org JSON-LD objects. Ensure runtime and compile-time accuracy for your structured search data, metadata serialization, and dynamic JSON-LD injection.
Features
- Full Type-Safety: Autogenerated TypeScript definitions directly compiled from the Schema.org vocabulary.
- Validation & Typeguards: Helper utilities to validate and assert schema structures.
- Hydration: Automatically insert missing
@typeproperties onto nested objects. - Serialization/Deserialization: Seamless translation to and from JSON-LD strings with automatically resolved
@context.
Installation
npm install @antinna/schema-ld-typesUsage Examples
Here are some standard ways to validate, serialize, deserialize, and check types for 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 object 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 Person
console.log(`Successfully verified Person: ${data.name}`);
} else {
console.error("Invalid Person structure!");
}3. Assertion Testing
Throws an error if the object does not conform to the expected 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 prepends the correct @context to your structured data.
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
Parses a JSON-LD string and automatically hydrates missing nested @type properties recursively based on Schema.org 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"Funding and Sponsorship
If you find this library useful, please consider supporting the project and its development!
License
This project is licensed under the MIT License.
