NodeJS 类型“ReadStream”不能赋给类型“string”,ts(2322)

kmb7vmvb  于 2023-01-30  发布在  Node.js
关注(0)|答案(1)|浏览(169)

我正在尝试运行以下代码:

const uploadParams = {Bucket: bucketName, Key: '', Body: ''};
const file = '/home/a/bars/img1.png';

const fileStream = fs.createReadStream(file);
fileStream.on('error', function(err) {
  console.log('File Error', err);
});
uploadParams.Body = fileStream;
var path = require('path');
uploadParams.Key = path.basename(file);

但是我在代码的uploadParams.Body = fileStream;行得到以下错误:

Type 'ReadStream' is not assignable to type 'string'.ts(2322)

我该怎么补救呢?

nfs0ujit

nfs0ujit1#

只需指定对象键Body可以保存的类型,如下所示:

{ Bucket: string; Key: string; Body: string | ReadStream }

解决方案:

import fs, { ReadStream } from "fs";
import path from "path";

const bucketName = '';
const uploadParams: { Bucket: string; Key: string; Body: string | ReadStream } = {
  Bucket: bucketName,
  Key: '',
  Body: '',
};
const file = '/home/a/bars/img1.png';

const fileStream = fs.createReadStream(file);
fileStream.on('error', function (err) {
  console.log('File Error', err);
});
uploadParams.Body = fileStream;
uploadParams.Key = path.basename(file);

或者,如果使用require,则可以使用typeof关键字:

// { Bucket: string; Key: string; Body: string | typeof ReadStream } 

const { ReadStream } = require("fs");
const fs = require("fs");
const path = require("path");

const bucketName = '';
const uploadParams: { Bucket: string; Key: string; Body: string | typeof ReadStream } = {
  Bucket: bucketName,
  Key: '',
  Body: '',
};
const file = '/home/a/bars/img1.png';

const fileStream = fs.createReadStream(file);
fileStream.on('error', function (err) {
  console.log('File Error', err);
});
uploadParams.Body = fileStream;
uploadParams.Key = path.basename(file);

虽然我觉得用空字符串来保存流很奇怪,但为什么不直接这么做呢?

const uploadParams: { Bucket: string; Key: string; Body: null | ReadStream } = {
  Bucket: bucketName,
  Key: '',
  Body: null,
};

示范-TSPlayground

相关问题