1

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.

1 Answer 1

3

Specify the return type in the function declaration:

export = function(data: ISomethingB): ISomethingA {
    return {
      limit: 4,
      values: {}
    };
};
Sign up to request clarification or add additional context in comments.

2 Comments

ah yes, thanks, I really like the idea of the "as" notation, but I cannot see any good use cases for it
The as notation is telling the compiler that "hey, I know you think that object is of type X, but I want you to treat it as type Y". That's why you can use "as" for this purpose.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.