Working with YAML in TypeScript: parsing, generation, and validation
YAML (YAML Ain't Markup Language) is one of the most popular data serialization formats, actively used in configuration files, DevOps (Docker, Kubernetes, Ansible), and CI/CD pipelines. In the TypeScript ecosystem, the js-yaml library is used for working with YAML, providing full support for the YAML 1.2 specification, including complex structures, tags, and custom data types.
Installation and setup
To get started, install the library and its types via npm:
npm install js-yamlnpm install --save-dev @types/js-yamlAfter installation, you can import the library into your TypeScript project:
import * as yaml from 'js-yaml';import * as fs from 'fs';Parsing YAML in TypeScript
The main function for reading YAML is yaml.load(), which converts a YAML string into a JavaScript/TypeScript object. Consider an example with a configuration file:
// config.yaml// server:// port: 3000// host: "localhost"// database:// url: "mongodb://localhost:27017/mydb"// poolSize: 10// features:// - logging// - authentication
interface Config { server: { port: number; host: string; }; database: { url: string; poolSize: number; }; features: string[];}
const yamlContent = fs.readFileSync('config.yaml', 'utf8');const config = yaml.load(yamlContent) as Config;
console.log(config.server.port); // 3000console.log(config.features); // ['logging', 'authentication']For safe parsing (without code execution), use yaml.load() — it is safer than yaml.eval(), which can execute arbitrary JavaScript code.
Generating YAML from TypeScript objects
The reverse operation — converting a TypeScript object into a YAML string — is performed by the yaml.dump() function. This is useful for creating configuration files on the fly:
interface DeploymentConfig { apiVersion: string; kind: string; metadata: { name: string; labels?: Record<string, string> }; spec: { replicas: number; selector: Record<string, string> };}
const deployment: DeploymentConfig = { apiVersion: 'apps/v1', kind: 'Deployment', metadata: { name: 'my-app', labels: { app: 'my-app', tier: 'backend' } }, spec: { replicas: 3, selector: { matchLabels: { app: 'my-app' } } }};
const yamlString = yaml.dump(deployment, { indent: 2, lineWidth: 120, noRefs: true, sortKeys: true});
console.log(yamlString);// apiVersion: apps/v1// kind: Deployment// metadata:// labels:// app: my-app// tier: backend// name: my-app// spec:// replicas: 3// selector:// matchLabels:// app: my-appWorking with custom types
The js-yaml library supports custom schemas and data types. This is especially useful when working with dates, regular expressions, or special objects:
import * as yaml from 'js-yaml';
// Create a custom type for datesconst DateType = new yaml.Type('!date', { kind: 'scalar', resolve: (data: string) => !isNaN(Date.parse(data)), construct: (data: string) => new Date(data), instanceOf: Date, represent: (date: Date) => date.toISOString()});
// Create a schema with support for standard and custom typesconst schema = yaml.DEFAULT_SCHEMA.extend([DateType]);
const yamlWithDates = `event: !date 2024-12-25T10:00:00Ztitle: "Christmas seminar"`;
const parsed = yaml.load(yamlWithDates, { schema });console.log(parsed.event instanceof Date); // trueconsole.log(parsed.event.toLocaleDateString('en-US')); // 12/25/2024YAML validation with
Also in library
Java WebSocket Libraries: Complete Guide to Real-Time Implementation
Sending SMS in Java: Overview and Examples of Using API Libraries (Twilio, Nexmo)
Machine Learning in Go: Overview of Libraries for Golang
Sending Email in C++: libcurl and SMTP Clients
Sending Email in TypeScript: Libraries and Code Examples