简体   繁体   English

可以使用方括号表示法访问模块属性,但不能使用点属性表示法

[英]Can access module property with square bracket notation but not with dot property notation

I'm exporting a function from a controller file:我正在从 controller 文件中导出 function :

import adminSaveSnippet from './admin/adminSaveSnippet';
exports.saveSnippet = adminSaveSnippet;

I am importing the function into my routing file:我将 function 导入到我的路由文件中:

import * as express from 'express';
const adminRouter = express.Router();
import * as admin from '../controllers/adminControllers';

adminRouter.put('/save/snippet', admin['saveSnippet']);

export default adminRouter;

I can access the saveSnippet function in admin via admin['saveSnippet'] but when I use dot notation admin.saveSnippet I get the following error:我可以通过admin['saveSnippet']admin中访问saveSnippet function 但是当我使用点符号admin.saveSnippet时,我收到以下错误:

src/routes/admin.ts:5:40 - error TS2339: Property 'saveSnippet' does not exist on type 'typeof import(".../src/controllers/adminControllers")'.

I am not really sure what is going on.我不确定发生了什么。 I am not using anyirregular identifiers and I have tried several different ways of exporting the function (eg, import { saveSnippet } from '../controllers/adminControllers' ) but still get the same error.我没有使用任何不规则标识符,并且我尝试了几种不同的方法来导出 function(例如import { saveSnippet } from '../controllers/adminControllers' ),但仍然得到相同的错误。

For completeness here is my adminSaveSnippet file:为了完整起见,这里是我的 adminSaveSnippet 文件:

export default function adminSaveSnippet (_req, res) {

  console.log('here');
  res.send('saved').status(200);
}

This is most probably just a TypeScript syntax issue.这很可能只是 TypeScript 语法问题。

In your adminControllers.ts file, try the export syntax, like you have done in your adminSaveSnippet file, instead of the CommonJS exports :在您的 adminControllers.ts 文件中,尝试export语法,就像您在 adminSaveSnippet 文件中所做的那样,而不是 CommonJS exports

export {
  adminSaveSnippet as saveSnippet
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM