node.js - ES6 * typescript : Cannot find namespace

标签 node.js typescript ecmascript-6

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;

最佳答案

const heroRouter = new HeroRouter();
const router = heroRouter.router;
export default router;

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

关于node.js - ES6 * typescript : Cannot find namespace,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42049783/

相关文章:

javascript - 使用 node.js 进行长轮询并表达 : how to cache res object into redis or other cache framework

typescript - 0x800a01b6 - JavaScript 运行时错误 : Object doesn't support property or method

javascript - 将 JavaScript 代码转换为 React 组件类格式

javascript - 具有条件的数组的总和

javascript - React Native for 循环获取索引

javascript - Sails.js 对关联值的查询

node.js - Express 和 Redis session 的过期时间

javascript - 使用 _.each 将动态属性添加到 Mongoose 结果中

typescript - 条件类型与可选属性不能很好地配合

node.js - get 的响应数据类型