【问题标题】:How to pattern-match on `UploadedFile | UploadedFile[]`如何在 `UploadedFile | 上进行模式匹配上传文件[]`
【发布时间】:2020-08-07 08:29:20
【问题描述】:

我正在尝试使用 TypeScript express-fileuploadbody-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


【解决方案1】:

你可以使用 instanceof 操作符。它用于在运行时检查对象的类型。

所以你的代码应该是这样的

if(form instanceof Array){
// code to be executed for array of files
}else{
// code to be executed for one file object
}

你可以阅读更多关于它的信息 https://www.geeksforgeeks.org/instanceof-operator-in-javascript/

【讨论】:

  • 我实际上希望有一个更符合 Typescript 习惯的解决方案,但无论如何感谢。这可能是我可以求助的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-08
  • 2015-04-02
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多