typescript 打字稿 csv-parse

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39488102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 03:50:50  来源:igfitidea点击:

Typescript csv-parse

csvtypescripttypescript-typings

提问by niklas

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.

我正在尝试使用我完全陌生的打字稿解析 csv 文件。我无法让解析器使用正确的类型。

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:

但是当涉及到打字稿时,我遇到了错误,我从 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?

任何人都可以给我一个提示或在打字稿之前使用 csv-parse 并分享他们的代码吗?

回答by Ross Scott

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:

这只是一个简单的转换问题,您的所有代码都是正确的,只是 TS 需要帮助了解从 CsvParse 返回的内容。如果你看一下定义文件,它的返回签名是void|parse.CsvParser. 因此,要告诉 TS 它实际上是一个 CsvParser(而不是 void),只需将其强制转换即可:

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

回答by jajones

I was running into a different problem and had to change the index.d.ts in @types/csv-parse from:

我遇到了一个不同的问题,不得不将 @types/csv-parse 中的 index.d.ts 更改为:

export = parse;

to:

到:

export default parse;

This allowed me to access the parse function and pass it to the fs stream properly.

这使我能够访问 parse 函数并将其正确传递给 fs 流。