How to use TypeScript with Loopback

2019-04-06 02:01发布

问题:

I'm using Loopback from Strongloop as a REST framework and ORM. I want to use TypeScript for my business logic. However, Loopback requires JavaScript with a specific shape to support their framework. For example:

module.exports = function(Person){

    Person.greet = function(msg, cb) {
      cb(null, 'Greetings... ' + msg);
    }

    Person.remoteMethod(
       'greet', 
        {
          accepts: {arg: 'msg', type: 'string'},
          returns: {arg: 'greeting', type: 'string'}
        }
    );
}; 

What is the TypeScript code that will generate the above JavaScript code?

回答1:

What is the TypeScript code that will generate the above JavaScript code?

You can just use this code as it is (JavaScript is TypeScript). If you are curious about module.export you can use TypeScript's --module commonjs compile flag to get that in a Typeaware manner like this:

function personMixin(Person){
    Person.greet = function(msg, cb) {
      cb(null, 'Greetings... ' + msg);
    }

    Person.remoteMethod(
       'greet', 
        {
          accepts: {arg: 'msg', type: 'string'},
          returns: {arg: 'greeting', type: 'string'}
        }
    );
};

export = personMixin; // NOTE!

Here is a tutorial on TypeScript module patterns : https://www.youtube.com/watch?v=KDrWLMUY0R0&hd=1