Home > Net >  destructure with typedEvent in typescript
destructure with typedEvent in typescript

Time:01-22

In the 3rd party lib, There's the following:

export interface Event extends Log {
    args?: Result;
}

export interface TypedEvent<EventArgs extends Result> extends Event {
  args: EventArgs;
}

export type InstallationPreparedEvent = TypedEvent<
[
   string,
   string
] & {
   sender: string;
   permissions : string;
}
>;

Then, in my code, I got this.

function prepareInstall(...): Promise<InstallationPreparedEvent> {
   const event = ...;
   return event;
}

Then, I got these choices, but I like none of them. The reason is, I simplified it, but it actualy contains 8 args, so code becomes ugly.

// choice 1.
function run() {
   const event = await prepareInstall();
   string sender = event.args.sender;
}

// choice 2
function run() {
   const { event : {sender } } = await prepareInstall();
}

// choice 3
function run() {
   const { sender } = (await prepareInstall()).args;
}

What I want to achieve is from prepareInstall, I want to return event.args directly so I'd use it like this:

const { sender } = await prepareInstall();

But returning event.args doesn't solve it as typescript in the run still requires me to do: event.args.sender. The important thing is I need returned type in prepareInstall to be InstallationPreparedEvent since in run, I want typescript to tell me what values exist(sender, permissions).

Hope I made sense.

CodePudding user response:

If I understand correctly, you want to return only the arg prop from InstallationPreparedEvent, but with correct typing (right?).

You can specify a prop's type through bracket notation:

function prepareInstall(...): Promise<InstallationPreparedEvent["args"]> {
   const event = await ...;
   return event.args;
}

With this, you will get type hinting:

function run() {
   const eventArgs = await prepareInstall();
   const {sender} = eventArgs; // no complaints
   const foo = eventArgs.foo; //Error: Property 'foo' does not exist on type '[string, string] & { sender: string; permissions: string; }'
}
  • Related