简体   繁体   English

生成强类型函数时,节点 api 服务上出现意外标记“:”

[英]Unexpected token ':' on an node api service when making a function strongly typed

I have a node api service written in typescript, below is my sample code我有一个用打字稿编写的节点 api 服务,下面是我的示例代码

class dataStreamConfig {
    constructor() { }

    conclaveObj = (firstParam: string, secondParam: number, thirdParam: any): any => {
        //my business logic goes here
       //return Obj

    };
}

module.exports = dataStreamConfig ;

Im getting the below error我收到以下错误

SyntaxError: Unexpected token ':'
    at Module._compile (internal/modules/cjs/loader.js:891:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)

If i remove the types (string, number, any) from the function, then it is working fine.如果我从函数中删除类型(字符串、数字、任何),那么它工作正常。 I have tried to redo npm install.我试图重做 npm install。

Also i did npm install babel-cli babel-preset-es2015.我也做了 npm install babel-cli babel-preset-es2015。

Update更新

Below is my tsconfig.json下面是我的 tsconfig.json

{
    "compilerOptions": {
      "target": "es5",
      "module": "commonjs",
      "sourceMap": true
    }
  }

Also i have typescript installed globally.我还全局安装了打字稿。 I compile the project using tsc command at the root, also i have tried running tsc on the directory which has the class.我在根目录下使用 tsc 命令编译项目,我也尝试在具有该类的目录上运行 tsc。

Would really appreciate any help / suggestion in this issue.非常感谢在这个问题上的任何帮助/建议。

try getting rid of the arrow function and using the normal way of writing a function with the function keyword .. Do note the last any in this function denotes the type this function will return and this is optional.尝试摆脱箭头函数并使用使用 function 关键字编写函数的正常方式.. 请注意此函数中的最后一个 any 表示此函数将返回的类型,这是可选的。 typescript can also detect this itself.打字稿本身也可以检测到这一点。 so it doesn't matter if you provide it or not...所以你是否提供它并不重要......

class dataStreamConfig {
constructor() { }

   let conclaveObj = function (firstParam: string, secondParam: number, thirdParam: any): any {
    //my business logic goes here
   //return Obj

};

}

module.exports = dataStreamConfig ;

for more help you can visit thier documentation ... https://www.typescriptlang.org/docs/handbook/functions.html如需更多帮助,您可以访问他们的文档... https://www.typescriptlang.org/docs/handbook/functions.html

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

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