iTranslated by AI
Tackling CSV Type Chaos: Achieving Full Type Safety in TypeScript
Introduction
I will introduce how to handle CSV files type-safely in TypeScript, including concrete implementations.
You can check the demo and the actual source code for the code introduced in this article here.

CSV Struggles: Why Doesn't It Work Like JSON?
JSON files are very easy to handle in TypeScript projects.
Just by writing import data from './data.json', TypeScript infers the type, and you can use the contents directly as an object.
It's very convenient.
However, it doesn't work that way with CSV files.
While CSV is structured text data, there is no standard mechanism to import it directly and handle it as an object like JSON.
Therefore, when handling CSV on the server side, in many cases, you end up using the fs module to read the file as a string and implement the parsing process yourself.
import fs from "node:fs";
import path from "node:path";
import { parse } from "papaparse"; // Example of a CSV parser
const csvPath = path.join(process.cwd(), "data", "sales_data.csv");
const csvFile = fs.readFileSync(csvPath, "utf-8");
const { data } = parse(csvFile, { header: true });
// data will be any[] or Record<string, any>[], which is not type-safe
data.forEach((row) => {
console.log(row.productName); // ❌️ Property existence is unknown. Type completion doesn't work...
});
In this method, the content of data becomes an array of any, and property names or value types are not guaranteed at all.
This significantly reduces the benefits of using TypeScript.
Type-Safe CSV Parsing with Valibot
To solve this challenge, we combine a CSV parser with a schema validation library.
In this case, let's use Valibot, which I use frequently.
As I mentioned in the Conform article, Valibot is a very lightweight and performance-oriented validation library.
I had an AI prepare the following data for me.
itemId,productName,category,unitPrice,salesCount,saleDate
P001,高性能ノートPC,PC・周辺機器,150000,5,2025-05-10
P002,ワイヤレスイヤホン,オーディオ,12000,30,2025-05-11
P003,"多機能バックパック, 30L",バッグ・アクセサリ,8500,15,2025-05-12
P004,有機栽培コーヒー豆 500g,食品・飲料,2200,50,2025-05-12
P005,ゲーミングマウス,PC・周辺機器,7800,25,2025-05-13
P006,小説「夏空の約束」,書籍,1650,120,2025-05-14
P007,スマートウォッチ,ウェアラブル,25000,18,2025-05-15
P008,"アロマディフューザー, ウッド調",生活家電,4500,40,2025-05-16
P009,天然水 2L (6本入),食品・飲料,800,200,2025-05-17
P010,グラフィックTシャツ,ファッション,3200,60,2025-05-18
First, we define a schema for the structure that the CSV row data should have.
This schema defines the type for a single row of the CSV.
import * as v from "valibot";
const salesDataSchema = v.object({
itemId: v.string(),
productName: v.string(),
category: v.string(),
unitPrice: v.number(),
salesCount: v.number(),
saleDate: v.string(),
});
export type SalesData = v.InferOutput<typeof salesDataSchema>;
Next, we implement the parsing process using this schema.
import fs from "node:fs";
import path from "node:path";
import papa from "papaparse";
import * as v from "valibot";
import { salesDataSchema, type SalesData } from "./schema";
export const getSalesData = (): SalesData[] => {
const csvPath = path.join(process.cwd(), "data", "sales_data.csv");
const csvFile = fs.readFileSync(csvPath, "utf-8");
const { data } = papa.parse(csvFile, {
header: true,
dynamicTyping: true, // Automatically converts types for numbers and dates
});
// Validate and transform data with Valibot
const validationResult = v.safeParse(v.array(salesDataSchema), data);
if (!validationResult.success) {
// In a real application, implement more thorough error handling
console.error(validationResult.issues);
throw new Error("CSV data validation failed");
}
// The resulting data here is completely type-safe!
return validationResult.output;
};
Basic type conversion is performed using papaparse's dynamicTyping option, and the results are validated and formatted using the Valibot schema.
This completely guarantees that the return value of getSalesData is of type SalesData[], allowing you to fully utilize the editor's type completion.
Implementation Points and Supplements
There are a few points worth knowing when dealing with this method.
Server-side Execution Prerequisite and Build-time Behavior
Since this code depends on Node.js's fs module, it assumes execution on the server side where Node.js is running.
There is one interesting point here.
When using this code in a React Server Components (RSC) environment like Next.js, fs.readFileSync is executed only once during the build, not for every request.
Therefore, while it looks like it's reading the file dynamically, unless you explicitly invalidate the cache with revalidatePath or revalidateTag, the behavior is essentially the same as if the content were bundled into the build output.
Smart Loading in Vite Environment
If you are using Vite for frontend development, there is an even simpler method.
By using the ?raw suffix, you can directly import the bundled CSV file as a string.
import csvString from "./sales_data.csv?raw";
To use this feature, you need to tell TypeScript the type using an ambient declaration.
declare module "*.csv?raw" {
const content: string;
export default content;
}
This eliminates the need for the fs module and allows you to describe similar parsing processes simply on the client side.
Benefits of This Approach
The biggest advantage of this method is that any CSV data can be handled type-safely.
-
Works for both local files and dynamic data
While we handled a local CSV file this time, you can apply the exact same validation logic when parsing a CSV string obtained from an API. This helps prevent unexpected errors caused by external data sources. -
Ultimate Developer Experience
When writing code likedata.productName, the editor suggests properties. Bugs caused by typos are now a thing of the past.
Summary
CSV files are difficult for TypeScript to handle as they are, but by combining a CSV parser with a schema validation library like Valibot, it becomes possible to handle them type-safely and comfortably, just like JSON.
This is a technique that can be applied to various environments, not just server-side data processing, depending on your ingenuity.
I hope you enjoy a type-safe CSV life in your projects!
Discussion