如何编写打字稿方法来复制javascript方法

我在JavaScript中有这样的代码:

// find the user User.findOne({ name: req.body.name }, function(err, user) { if (err) throw err; if (!user) { res.json({ success: false, message: 'Authentication failed. User not found.' }); } else if (user) { //issue token } }) 

User.findOne来mongoose。 但是我想嘲笑这个方法,所以我现在不会和数据库进行交stream。 但要保持这样的逻辑,所以我需要写我自己的User.findOne打字稿模拟,所以是相同的。

这就是我到目前为止:

 export class User { constructor() { } public findOne(user: any, next:Function) { console.log(1); //getting there var fake = {name: "a", password: "p"}; return fake; } } 

我正在导入我的代码

 import {User} from '../mock/User'; var login = {name: req.body.name, password: req.body.password} //fake // find the user User.prototype.findOne({ user: login }, function(err, user) { console.log(2); //not getting there when using my User.findOne from .ts ........ } 

但是function(err, user)后面的代码function(err, user)只是没有被执行。

你有什么想法如何解决?

更新:试图使用lambdas但仍然是相同的问题:

 User.findOne({user: login}, (err, user) => { console.log("test"); //- this code inside function just not executed }) 

如果您希望直接从User类调用该方法,而不是从实例中调用,则需要将其声明为静态。

 public static findOne(user: any, next:Function) { console.log(1); //getting there var fake = {name: "a", password: "p"}; next(undefined,fake); //this will call the function you passed as lambda or regular function } 

这样你可以调用这样的方法。

 User.findOne({},(error,result)=>{ //using a lambda here to make sure you have no issues with 'this' but you can also pass a regular function object. console.log(result); console.log(error); } 

尝试User名为findOne(err, user)静态方法在user.ts定义一个名为User的类:

user.ts

 export class User { constructor(){} static findOne(query, user: Function) { // whatever } } 

使用它作为:

 import * as User from './path/user' User.findOne({...}, (err, user) => { // whatever }) 

除此之外,我发现一个小技巧非常有用:使用typescript来定义你的callback的签名,而不仅仅是Function ,定义你的cb的参数; 例如:

user.ts

 export class User { // callback function has 2 arguments: err and user (you can specify their types too static findOne(query: any, cb: (err: any, user: any) => void) { // whatever } }