0

I am trying to run the following code:

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);

But I get the following error at uploadParams.Body = fileStream; line of the code:

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

How can I fix this?

best_of_man
  • 643
  • 2
  • 15
  • You are assigning fileStream to a string when you declare the uploadParams object. `const uploadParams = {Bucket: bucketName, Key: '', Body: ''};` here. So, do `Body: null` in the initialization instead. Should get rid of the TS error. Or just do: `const uploadParams: {Bucket: string, Key: string, Body: ReadStream | string } = {Bucket: bucketName, Key: '', Body: ''};` – Joel Jan 28 '23 at 17:29
  • @Joel: Didn't work! Still get an error for `Body: ''` says `Type 'string' is not assignable to type 'ReadStream'.ts(2322)` – best_of_man Jan 28 '23 at 17:51

1 Answers1

0

Just specify what type the object-key Body can hold like this:

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

Solution:

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);

Or if you use require you can use the typeof keyword:

// { 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);

Although I find it strange that you use an empty string to hold a stream. Why not just do?

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

Demo - TS Playground

Joel
  • 5,732
  • 4
  • 37
  • 65