Home > Net >  TypeScript Interface implement on function?
TypeScript Interface implement on function?

Time:06-16

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.

CodePudding user response:

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.

CodePudding user response:

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: ... {
    }
  }
  • Related