【发布时间】:2020-08-07 08:29:20
【问题描述】:
我正在尝试使用 TypeScript express-fileupload 和 body-parser 实现文件上传。 (我也成功安装了对应的@types)。
我正在努力将 JavaScript 示例转换为 TypeScript,但我认为我的问题更普遍。我想使用(见代码)是form.mv() 和form.name,但编译器一直抱怨这些成员不存在。查看我的form 变量的类型,它是UploadedFile | UploadedFile[] 的联合类型,所以我认为我必须在运行时根据实际类型情况进行切换。但是编译器不允许我对它实际推断的类型案例进行模式匹配(参见屏幕截图)。处理这种类型的正确方法是什么?
截图:
完整代码:
import {Express, Request, Response} from 'express';
import fileUpload = require('express-fileupload');
import bodyParser = require('body-parser');
export class Server {
private app: Express;
constructor(app: Express) {
this.app = app;
this.app.use(fileUpload({createParentPath: true}));
this.app.use(bodyParser.json());
this.app.use(bodyParser.urlencoded({extended: true}));
this.app.post('/form', (req: Request, res: Response) => {
try {
if (!req.files) {
res.send({
status: false,
message: 'No form uploaded'
});
} else {
// use the name of the upload field to retrieve the uploaded form
let form = req.files.form;
// use the mv() method to place the file in the forms directory
switch (form) {
case fileUpload.UploadedFile: true;
case fileUpload.UploadedFile[]: false
}
form.mv('./forms/' + form.name);
}
}
});
}
public start(port: number): void {
this.app.listen(port, () => console.log(`Server listening on port ${port}!`));
}
}
【问题讨论】:
-
@wiktor-stribizew 我看过
pattern-matching标签的描述,它是关于数据结构和FP,而不是正则表达式。为什么要删除它?
标签: typescript file-upload pattern-matching