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

Time:01-29

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?

CodePudding user response:

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

  • Related