Alexander Mills
Alexander Mills

Reputation: 100020

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.

Upvotes: 1

Views: 54

Answers (1)

Robby Cornelissen
Robby Cornelissen

Reputation: 97150

Specify the return type in the function declaration:

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

Upvotes: 3

Related Questions