Working with CSV in TypeScript: A Complete Guide
CSV (Comma-Separated Values) is one of the most popular formats for exchanging tabular data. In TypeScript (and JavaScript), there are several powerful libraries for parsing, generating, and processing CSV files. In this article, we will look at the main tools, their capabilities, and provide practical examples.
Why use libraries for CSV?
Built-in JavaScript tools (e.g., split(',')) do not handle complex cases:
- Escaped quotes and commas within fields
- Different delimiters (semicolon, tab)
- Different encodings and BOM
- Multiline values
- Different line ending types (CRLF, LF)
Professional libraries solve all these problems and provide a convenient API for working with data.
1. csv-parse — CSV parsing in Node.js and the browser
csv-parse is part of the csv.js ecosystem, one of the most popular parsing libraries. It works both in Node.js and in the browser (via a bundler).
Installation
npm install csv-parseUsage example with TypeScript
import { parse } from 'csv-parse/sync';import { readFileSync } from 'fs';
interface User { id: number; name: string; email: string;}
const csvData = readFileSync('users.csv', 'utf-8');const records: User[] = parse(csvData, { columns: true, // first row is headers skip_empty_lines: true, delimiter: ',', cast: (value, context) => { if (context.column === 'id') return parseInt(value, 10); return value; }});
console.log(records);2. PapaParse — universal parser for browser and Node.js
PapaParse is a library with excellent support for large files (streaming processing), automatic delimiter detection, and extensive configuration options.
Installation
npm install papaparseExample with result typing
import Papa from 'papaparse';
interface Product { sku: string; price: number; quantity: number;}
const csvString = `sku,price,quantityABC-001,29.99,100ABC-002,49.50,50`;
const result = Papa.parse<Product>(csvString, { header: true, dynamicTyping: true, // automatic type conversion skipEmptyLines: true});
if (result.errors.length > 0) { console.error('Parsing errors:', result.errors);} else { result.data.forEach(product => { console.log(`Product ${product.sku}: ${product.price} RUB`); });}3. csv-stringify — generating CSV from data
For the reverse task — creating CSV from arrays of objects — use csv-stringify. It is also part of the csv.js ecosystem.
Installation
npm install csv-stringifyCSV generation example
import { stringify } from 'csv-stringify/sync';import { writeFileSync } from 'fs';
interface Order { orderId: number; customer: string; total: number;}
const orders: Order[] = [ { orderId: 1001, customer: 'Ivan Petrov', total: 1500.50 }, { orderId: 1002, customer: 'Maria Sidorova', total: 2300.00 }, { orderId: 1003, customer: 'Alexey Ivanov', total: 890.75 }];
const csvOutput = stringify(orders, { header: true, columns: ['orderId', 'customer', 'total']});
writeFileSync('orders.csv', csvOutput, 'utf-8');console.log('CSV file created successfully');4. Error handling and data validation
When working with CSV, it is important to handle errors correctly. Let's look at an example with data validation:
import Papa from 'papaparse';
interface ValidatedRow { isValid: boolean; errors: s Also in library
Database Migrations in TypeScript: A Complete Guide to Tools and Approaches
Working with Excel in Java: Apache POI and Alternatives
Task Queues in Java: ExecutorService and ThreadPoolExecutor
Working with Kafka in Rust: Libraries and Examples for Beginners