Working with CSV in TypeScript: A Complete Guide
CSV (Comma-Separated Values) is one of the most common formats for exchanging tabular data. In the TypeScript ecosystem, there are several mature libraries that allow you to efficiently parse, generate, and transform CSV files with full type support. In this article, we will look at three main tools: csv-parse, csv-stringify, and papaparse, and also analyze practical examples of their use.
1. The csv-parse Library: Parsing CSV with Typing
csv-parse is part of the csv.js ecosystem, one of the most performant libraries for parsing CSV. It supports streams, custom delimiters, and strict typing via TypeScript.
Installation:
npm install csv-parsenpm install @types/csv-parse // for TypeScript (if not included automatically)Example of parsing a CSV string:
import { parse } from 'csv-parse/sync';import { stringify } from 'csv-stringify/sync';
interface User { id: number; name: string; email: string; age: number;}
const csvData = `id,name,email,age1,Ivan Ivanov,ivan@example.com,302,Maria Petrova,maria@example.com,253,Alexey Smirnov,alex@example.com,35`;
// Parsing with explicit type declarationconst records: User[] = parse(csvData, { columns: true, // first row is headers skip_empty_lines: true, delimiter: ',', cast: true // automatic type casting (strings to numbers)});
console.log(records);// [// { id: 1, name: 'Ivan Ivanov', email: 'ivan@example.com', age: 30 },// { id: 2, name: 'Maria Petrova', email: 'maria@example.com', age: 25 },// { id: 3, name: 'Alexey Smirnov', email: 'alex@example.com', age: 35 }// ]2. The csv-stringify Library: Generating CSV from Objects
csv-stringify is a companion library for creating CSV strings and files from arrays of objects or tuples. It is excellent for data export.
Example of CSV generation:
import { stringify } from 'csv-stringify/sync';
interface Product { sku: string; price: number; stock: number;}
const products: Product[] = [ { sku: 'PRD-001', price: 1500, stock: 10 }, { sku: 'PRD-002', price: 2500, stock: 5 }, { sku: 'PRD-003', price: 800, stock: 20 },];
const csvOutput = stringify(products, { header: true, columns: ['sku', 'price', 'stock'], // field order and filtering});
console.log(csvOutput);// sku,price,stock// PRD-001,1500,10// PRD-002,2500,5// PRD-003,800,203. The PapaParse Library: A Universal Parser for Browser and Node.js
PapaParse is the most popular library for working with CSV in JavaScript/TypeScript. It works both in the browser and in Node.js, supports large files via streams, automatic delimiter detection, and error handling.
Installation:
npm install papaparsenpm install @types/papaparseExample with file processing in Node.js:
import fs from 'fs';import Papa from 'papaparse';
interface Transaction { date: string; amount: number; category: string;}
const fileContent = fs.readFileSync('transactions.csv', 'utf-8');
const result = Papa.parse<Transaction>(fileContent, { header: true, dynamicTyping: true, // automatic type conversion skipEmptyLines: true,});
if (result.errors.length > 0) { console.error('Parsing errors:', result.errors);} else { console.log('Transactions:', result.data); // result.data — array of Transaction objects}
// Asynchronous parsing with streams for large filesconst stream = fs.createReadStream('large-file.csv');Papa.parse(stream,