### TypeScript tserialize Configuration Example Source: https://context7.com/soeasy/tserialize/llms.txt Demonstrates advanced configuration options for tserialize in TypeScript, including handling null values, auto-creating models for raw data, and controlling instance creation during deserialization. This snippet showcases how to customize serialization behavior using options like `allowNullValues` and `autoCreateModelForRawData`. ```typescript import { serialize, deserialize, JsonName } from 'tserialize'; class ConfigExample { @JsonName('field1') field1: string; @JsonName('field2') field2: string | null; static fromServer(data: object): ConfigExample { return deserialize(data, ConfigExample); } } const instance = new ConfigExample(); instance.field1 = 'value'; instance.field2 = null; // Default behavior: null values excluded console.log(serialize(instance)); // Output: { field1: 'value' } // Allow null values in output console.log(serialize(instance, { allowNullValues: true })); // Output: { field1: 'value', field2: null } // Auto-create instances for raw data during serialization console.log(serialize(instance, { allowNullValues: true, autoCreateModelForRawData: true })); // Useful when serializing mixed arrays of instances and plain objects // Deserialization without creating instance (returns plain object) const plainObject = deserialize({ field1: 'test', field2: 'data' }, ConfigExample, { makeInstance: false }); console.log(plainObject instanceof ConfigExample); // false console.log(plainObject); // Plain object with properties mapped ``` -------------------------------- ### Map Flat Data to Composite Models with @JsonMeta (TypeScript) Source: https://context7.com/soeasy/tserialize/llms.txt The @JsonMeta decorator enables deserializing flat data into nested composite models by extracting specific fields from a parent object. It processes the entire parent data object, making it suitable for decomposing large, flat API responses into structured domain models. This example demonstrates mapping system and hardware information into a Computer class. ```typescript import { JsonName, JsonMeta, serialize, deserialize } from 'tserialize'; class SystemInfo { @JsonName('operating_system') osName: string; @JsonName('os_version') osVersion: string; @JsonName('kernel') kernel: string; } class HardwareInfo { @JsonName('cpu_model') cpu: string; @JsonName('ram_gb') ram: number; @JsonName('disk_gb') disk: number; } class Computer { @JsonName('computer_name') name: string; @JsonMeta(SystemInfo) system: SystemInfo; @JsonMeta(HardwareInfo) hardware: HardwareInfo; static fromServer(data: object): Computer { return deserialize(data, Computer); } toServer(): object { return serialize(this); } } // Flat data from API (all fields at the same level) const flatData = { computer_name: 'WorkStation-01', operating_system: 'Ubuntu', os_version: '22.04', kernel: '5.15.0', cpu_model: 'Intel i7-12700K', ram_gb: 32, disk_gb: 1000 }; const computer = Computer.fromServer(flatData); console.log(computer); // Output: { // name: 'WorkStation-01', // system: { osName: 'Ubuntu', osVersion: '22.04', kernel: '5.15.0' }, // hardware: { cpu: 'Intel i7-12700K', ram: 32, disk: 1000 } // } // Composite model with clean separation of concerns console.log(computer.system.osName); // 'Ubuntu' console.log(computer.hardware.ram); // 32 ``` -------------------------------- ### Serialize/Deserialize Arrays with @JsonArray (TypeScript) Source: https://context7.com/soeasy/tserialize/llms.txt The @JsonArray decorator handles the serialization and deserialization of arrays containing class instances. Each array element is processed using its class's `fromServer()` and `toServer()` methods if available, and invalid items are filtered during serialization. This example demonstrates managing a list of Task objects within a Project. ```typescript import { JsonName, JsonArray, serialize, deserialize } from 'tserialize'; class Task { @JsonName('task_id') id: number; @JsonName('title') title: string; @JsonName('completed') done: boolean; constructor(id?: number, title?: string, done?: boolean) { if (id !== undefined) { this.id = id; this.title = title; this.done = done; } } static fromServer(data: object): Task { return deserialize(data, Task); } toServer(): object { return serialize(this); } } class Project { @JsonName('project_name') name: string; @JsonArray(Task, 'tasks') taskList: Array = []; static fromServer(data: object): Project { return deserialize(data, Project); } toServer(): object { return serialize(this); } } // Deserialization from API const apiData = { project_name: 'Website Redesign', tasks: [ { task_id: 1, title: 'Design mockups', completed: true }, { task_id: 2, title: 'Implement frontend', completed: false }, { task_id: 3, title: 'Write tests', completed: false } ] }; const project = Project.fromServer(apiData); console.log(project.name); // 'Website Redesign' console.log(project.taskList.length); // 3 console.log(project.taskList[0] instanceof Task); // true console.log(project.taskList[0].title); // 'Design mockups' // Serialization to API project.taskList.push(new Task(4, 'Deploy to production', false)); project.taskList[1].done = true; const serialized = project.toServer(); console.log(serialized); // Output: { // project_name: 'Website Redesign', // tasks: [ // { task_id: 1, title: 'Design mockups', completed: true }, // { task_id: 2, title: 'Implement frontend', completed: true }, // { task_id: 3, title: 'Write tests', completed: false }, // { task_id: 4, title: 'Deploy to production', completed: false } // ] // } // Handling null values with configuration const emptyProject = new Project(); emptyProject.name = 'New Project'; emptyProject.taskList = null; console.log(serialize(emptyProject)); // {} console.log(serialize(emptyProject, { allowNullValues: true })); // { project_name: 'New Project', tasks: null } ``` -------------------------------- ### Serialize TypeScript Class Instances to Raw Data Source: https://context7.com/soeasy/tserialize/llms.txt Converts typed class instances back into plain JavaScript objects for API transmission. Only properties decorated with serialization decorators are included in the output; null and undefined values are excluded by default. Requires the `serialize` function and property decorators. ```typescript import { serialize, JsonName } from 'tserialize'; class Product { @JsonName('product_id') productId: number; @JsonName('product_name') productName: string; @JsonName('price') price: number; // Not decorated - won't be serialized internalCache: any; toServer(): object { return serialize(this); } } const product = new Product(); product.productId = 101; product.productName = 'Laptop'; product.price = 999.99; product.internalCache = { someData: 'ignored' }; const serialized = product.toServer(); console.log(serialized); // Output: { product_id: 101, product_name: 'Laptop', price: 999.99 } // Note: internalCache is not included ``` -------------------------------- ### Deserialize Data to TypeScript Class Instances Source: https://context7.com/soeasy/tserialize/llms.txt Converts raw data objects, typically from JSON APIs, into typed class instances. It leverages decorator metadata to apply transformations, handling nested structures, custom deserializers, and inheritance. Requires the `deserialize` function and property decorators like `@JsonName`. ```typescript import { deserialize, JsonName } from 'tserialize'; class User { @JsonName('first_name') firstName: string; @JsonName('last_name') lastName: string; @JsonName('age') age: number; getFullName(): string { return `${this.firstName} ${this.lastName}`; } static fromServer(data: object): User { return deserialize(data, User); } } // Raw data from API const rawData = { first_name: 'John', last_name: 'Doe', age: 30 }; // Transform to class instance const user = User.fromServer(rawData); console.log(user.firstName); // 'John' console.log(user.getFullName()); // 'John Doe' console.log(user instanceof User); // true ``` -------------------------------- ### Map Class Properties to Data Keys with @JsonName Source: https://context7.com/soeasy/tserialize/llms.txt The `@JsonName` decorator maps class properties to different keys in raw data, supporting optional custom transformation functions for both serialization and deserialization. It's the foundational decorator for handling naming conventions and data type conversions. ```typescript import { JsonName, serialize, deserialize } from 'tserialize'; class Employee { @JsonName() name: string; @JsonName('employee_id') id: number; @JsonName('salary', value => Math.round(value), // Serialize: round to integer value => parseFloat(value) // Deserialize: parse to float ) salary: number; @JsonName('is_active', value => value ? 'Y' : 'N', // Serialize: boolean to string value => value === 'Y' // Deserialize: string to boolean ) active: boolean; @JsonName('computed_field', () => null) // Never serialized tempField: string; static fromServer(data: object): Employee { return deserialize(data, Employee); } toServer(): object { return serialize(this); } } // Deserialization example const rawData = { name: 'Alice Smith', employee_id: 12345, salary: '75000.50', is_active: 'Y' }; const employee = Employee.fromServer(rawData); console.log(employee); // { name: 'Alice Smith', id: 12345, salary: 75000.5, active: true } // Serialization example employee.salary = 80000.75; employee.active = false; employee.tempField = 'ignored'; const serialized = employee.toServer(); console.log(serialized); // { name: 'Alice Smith', employee_id: 12345, salary: 80001, is_active: 'N' } ``` -------------------------------- ### TypeScript: Serialize Nested Objects with @JsonStruct Source: https://context7.com/soeasy/tserialize/llms.txt The @JsonStruct decorator in tserialize facilitates the serialization and deserialization of nested class instances. It automatically leverages the nested class's `fromServer()` and `toServer()` methods if they exist, otherwise, it uses the default `deserialize()` and `serialize()` functions. Custom raw data key names for nested objects are also supported. ```typescript import { JsonName, JsonStruct, serialize, deserialize } from 'tserialize'; class Address { @JsonName('street_name') street: string; @JsonName('city') city: string; @JsonName('postal_code') zipCode: string; static fromServer(data: object): Address { return deserialize(data, Address); } toServer(): object { return serialize(this); } } class Company { @JsonName('company_name') name: string; @JsonStruct(Address, 'headquarters') mainOffice: Address; @JsonStruct(Address, 'billing_address') billingAddress: Address; static fromServer(data: object): Company { return deserialize(data, Company); } toServer(): object { return serialize(this); } } // Deserialization const rawData = { company_name: 'Tech Corp', headquarters: { street_name: '123 Main St', city: 'San Francisco', postal_code: '94105' }, billing_address: { street_name: '456 Market St', city: 'San Francisco', postal_code: '94103' } }; const company = Company.fromServer(rawData); console.log(company.name); // 'Tech Corp' console.log(company.mainOffice instanceof Address); // true console.log(company.mainOffice.street); // '123 Main St' // Serialization const serialized = company.toServer(); console.log(serialized); // Output: // { // company_name: 'Tech Corp', // headquarters: { street_name: '123 Main St', city: 'San Francisco', postal_code: '94105' }, // billing_address: { street_name: '456 Market St', city: 'San Francisco', postal_code: '94103' } // } ``` -------------------------------- ### TypeScript: Mark Properties as Read-Only with @JsonNameReadonly Source: https://context7.com/soeasy/tserialize/llms.txt The @JsonNameReadonly decorator in tserialize marks properties that should only be deserialized from incoming data and never serialized back. This is useful for server-provided metadata or read-only identifiers. It supports custom raw data key names and optional value transformation functions. ```typescript import { JsonName, JsonNameReadonly, serialize, deserialize } from 'tserialize'; class Article { @JsonNameReadonly('article_id') id: number; @JsonNameReadonly('created_at', value => new Date(value)) createdAt: Date; @JsonNameReadonly('view_count') viewCount: number; @JsonName('title') title: string; @JsonName('content') content: string; static fromServer(data: object): Article { return deserialize(data, Article); } toServer(): object { return serialize(this); } } // From server const serverData = { article_id: 42, created_at: '2025-01-15T10:30:00Z', view_count: 1523, title: 'TypeScript Tips', content: 'Learn about decorators...' }; const article = Article.fromServer(serverData); console.log(article.id); // 42 console.log(article.viewCount); // 1523 console.log(article.createdAt instanceof Date); // true // Update editable fields article.title = 'TypeScript Best Practices'; article.content = 'Updated content...'; const toServer = article.toServer(); console.log(toServer); // Output: { title: 'TypeScript Best Practices', content: 'Updated content...' } // Note: id, createdAt, and viewCount are NOT included ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.