javascriptnode.jstypescripttypescript2.2

Use Typescript for API enforcement


I have a Node.js module that just looks like this:

module.exports = function(data){

    return {

      limit: 4,
      values: {}

    }


};

Using TypeScript, that might look like:

interface ISomethingA {
    values: Object,
    limit?: number
}

export = function(data: ISomethingB){

    return {

      limit: 4,
      values: {}

    } as ISomethingA;


};

These modules have to adhere to a certain API - the object returned from the function needs both "values" and a "limit" properties.

What TypeScript constructs can I use here to give users feedback so that they know they are adhering to the API?

The "as" syntax so far hasn't been working for me as I would have expected. I am looking for a way to define the type for the object that is returned from the function.


Solution

  • Specify the return type in the function declaration:

    export = function(data: ISomethingB): ISomethingA {
        return {
          limit: 4,
          values: {}
        };
    };