niklas niklas - 2 months ago 49
TypeScript Question

Typescript csv-parse

I am trying to parse a csv file with typescript which I am totally new to. I cannot get the parser working with the correct typings.

Without typings everything is easy:

var fs = require('fs');
var parse = require('csv-parse');

var parser = parse({delimiter: ';'}, function(err, data){
console.log(data);
});

fs.createReadStream(__dirname+'/fs_read.csv').pipe(parser);


But when it comes to typescript I get errors, I installed the typings from dt :

import * as csvParse from 'csv-parse';
import fs = require('fs');
var myParser:csvParse.CsvParser = csvParse({delimiter: ','}, function(data, err) {
console.log(data);
});


I get the error

Type 'void | CsvParser' is not assignable to type 'CsvParser'.


Can anyone give me a hint or used csv-parse with typescript before and share their code?

Answer

This is just a simple casting issue, all your code is right, its just TS needs help knowing what is being returned from CsvParse. If you take a look at the definition file, its return signature is void|parse.CsvParser. So to tell TS that it is actually a CsvParser (and not void) just cast it:

var myParser:csvParse.CsvParser = csvParse({delimiter: ','}, function(data, err) {
    console.log(data);
}) as csvParse.CsvParser;