0

Can someone confirm how to implement interface Iuser on function user. I know it is possible but not able to get through it.

interface IUser {
  infomation(): Promise<object>;
  groups(): Promise<object[]>;
}

//something like below implementation
function user(options?: Options): IUser {
  infomation: function infomation(): Promise<object> {
    ....;
  }
  groups: function groups(): Promise<object> {
    .....;
  }
}

Sorry if I wasn't clear on my question, what I am trying to do it here is trying to convert my JavaScript code to typed typescript code.

So that if I type

user(some options).

Then all functions under users will appear.

3
  • Can you add an example of how you intend to use this function and that interface? It's a little hard to know what "implement interface IUser on function user" actually means here. Commented Jun 15, 2022 at 20:50
  • Are you just trying to return that type so this would work? user({ option: 'a' }).groups()? Commented Jun 15, 2022 at 20:54
  • @AlexWayne, Yes that is what I am trying to do. Commented Jun 16, 2022 at 0:27

2 Answers 2

1

To implement that interface (assuming it's the return type, as you have set), you need to define a function that returns an object with 2 async functions.

What part of this do you not understand? We can answer more clearly.

Your functions return null. That's clearly not what the interface, or your self declared return type (Promise<object>) says.

Let's dig into one function:

   infomation: function infomation(): Promise<object> {
     return null;
   }

What is wrong with this picture? Your function returns null while your interface expects Promise<object>. Also, it's redundant to redeclare the return type your interface already does.

Anyways, null !== Promise<object>

So build what the interface requires: return a Promise that resolves to an object

return new Promise(() => ({imAnObject: true}))

Functions that return promises are handled with async, so that's probably what you're looking for:

 infomation: async function infomation(): {
     return {};
 }

Now repeat for the second function, which expects a slightly different return object.

Sign up to request clarification or add additional context in comments.

Comments

0

In addition to the above answer you can use Promise.resolve(), or Promise.resolve([]) for the other function.

The whole function should take the form of

return {
    infomation: ... {
    },
    groups: ... {
    }
  }

Comments

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.