【问题标题】:ES6 * Typescript : Cannot find namespaceES6 * Typescript:找不到命名空间
【发布时间】:2017-02-05 19:45:59
【问题描述】:

Node7.4.0 / ES6 / Typescript 2.1.5 / WebStorm 2016.3

上线: 导出默认 heroRoutes.router;

我明白了:TS2503 找不到命名空间“heroRoutes” 在创建它和 init() 之后 它有什么问题?

感谢反馈

HeroRouter.ts

import {Router, Request, Response, NextFunction} from 'express';
const Heroes = require('../data');

export class HeroRouter {
    router: Router;

    /**
     * Initialize the HeroRouter
     */
    constructor() {
        this.router = Router();
        this.init();
    }

    /**
     * GET all Heroes.
     */
    public  getAll(req: Request, res: Response, next: NextFunction) {
        res.send(Heroes);
    }

    /**
     * GET one hero by id
     */
    public getOne(req: Request, res: Response, next: NextFunction) {
        let query = parseInt(req.params.id);
        let hero = Heroes.find(hero => hero.id === query);
        if (hero) {
            res.status(200)
                .send({
                    message: 'Success',
                    status: res.status,
                    hero
                });
        }
        else {
            res.status(404)
                .send({
                    message: 'No hero found with the given id.',
                    status: res.status
                });
        }
    }

    /**
     * Take each handler, and attach to one of the Express.Router's
     * endpoints.
     */
    init() {
        this.router.get('/', this.getAll);
        this.router.get('/:id', this.getOne);
    }

}

// Create the HeroRouter, and export its configured Express.Router
let heroRoutes = new HeroRouter();
heroRoutes.init();

export default heroRoutes.router;

【问题讨论】:

    标签: node.js typescript ecmascript-6


    【解决方案1】:
    const heroRouter = new HeroRouter();
    const router = heroRouter.router;
    export default router;
    

    原因是您无法导出限定名称。 模块的导出绑定到称为模块命名空间对象的特殊对象。一个原因是,如果合格的导出是合法的,语义会令人惊讶,因为更新变量 heroRouter 的实例成员 router 的值不会更新导出绑定的值(这里命名为 default)。

    【讨论】:

    • 感谢 Aluan,这就是重点!我也不应该忘记在两个 const 声明之间插入 heroRouter.init() ......这里有什么意义?是否在导出默认参数中...指向某个文档的任何链接?...
    • 确实缺少一些上下文,我更新了我的答案
    • 至于init方法,我会去掉它,把所有的逻辑放在构造函数中。允许在无效状态下创建对象是一种不好的做法。它会导致错误,就像我的示例中的错误一样。
    • 非常感谢您的帮助 cmets... 可以重写为: const heroRouter = new HeroRouter().router;导出默认 heroRouter;
    • 是的,如果您删除 init 方法或使其链接实例并调用它。
    猜你喜欢
    • 2017-07-25
    • 2016-09-28
    • 1970-01-01
    • 2017-02-15
    • 2021-11-18
    • 2021-01-21
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    相关资源
    最近更新 更多