Working with CSV in TypeScript: Libraries and Code Examples

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

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, several powerful libraries are available that allow you to read, write, and transform CSV files with full type support. In this article, we will cover the main tools, their installation, and practical examples.



Popular Libraries for Working with CSV



The most commonly used libraries in the TypeScript/Node.js environment:



  • csv-parse — part of the csv suite, a reliable parser with stream support
  • papaparse — a universal parser for the browser and Node.js
  • csv-stringify — a CSV generator from arrays/objects
  • csvtojson — a CSV to JSON converter with typing


Installation and Setup



For TypeScript projects, installation is done via npm or yarn:



npm install csv-parse csv-stringify papaparse @types/papaparse


If you are using csv-parse, no additional types are required — the library has built-in TypeScript support.



Example 1: Parsing CSV with csv-parse



The csv-parse library is great for working with large files thanks to its stream API. Let's look at a basic example:



import { parse } from 'csv-parse/sync';import * as fs from 'fs';

interface User { id: number; name: string; email: string; age: number;}

const csvData = fs.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' || context.column === 'age') { return Number(value); } return value; }});

console.log(records);// [// { id: 1, name: 'Ivan', email: 'ivan@example.com', age: 30 },// { id: 2, name: 'Maria', email: 'maria@example.com', age: 25 }// ]


Example 2: Generating CSV with Typing



To create CSV files, use csv-stringify. Let's define a data type and generate a string:



import { stringify } from 'csv-stringify/sync';

interface Product { productId: string; name: string; price: number; inStock: boolean;}

const products: Product[] = [ { productId: 'P001', name: 'Laptop', price: 75000, inStock: true }, { productId: 'P002', name: 'Mouse', price: 1500, inStock: false }, { productId: 'P003', name: 'Keyboard', price: 3500, inStock: true }];

const csvOutput = stringify(products, { header: true, columns: ['productId', 'name', 'price', 'inStock']});

console.log(csvOutput);// productId,name,price,inStock// P001,Laptop,75000,true// P002,Mouse,1500,false// P003,Keyboard,3500,true


Example 3: Using PapaParse in the Browser



PapaParse is ideal for client-side CSV processing. An example with file upload via input:



import Papa from 'papaparse';

interface Transaction { date: string; amount: number; category: string; description: string;}

const fileInput = document.getElementById('csvInput') as HTMLInputElement;

fileInput.addEventListener('change', (event) => { const file = (event.target as HTMLInputElement).files?.[0]; if (!file) return;

Papa.parse<Transaction>(file, { header: true, dynamicTyping: true, // automatic type conversion skipEmptyLines: true, complete: (result) => { console.log('Parsing completed:', result.data); // result.data — array of Transaction objects }, error: (error) => { console.error('Parsing error:', error); } });});


Example 4:

Recommendations