[英]Type 'ReadStream' is not assignable to type 'string'.ts(2322)
我正在嘗試運行以下代碼:
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)
我怎樣才能解決這個問題?
只需指定對象鍵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);
雖然我覺得很奇怪,你用一個空字符串來保存一個stream。為什么不干脆呢?
const uploadParams: { Bucket: string; Key: string; Body: null | ReadStream } = {
Bucket: bucketName,
Key: '',
Body: null,
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.