簡體   English   中英

在 typescript 中使用 typedEvent 進行解構

[英]destructure with typedEvent in typescript

在第 3 方庫中,有以下內容:

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;
}
>;

然后,在我的代碼中,我得到了這個。

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

然后,我有這些選擇,但我都不喜歡。 原因是,我簡化了它,但它實際上包含 8 個參數,所以代碼變得難看。

// 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;
}

我想要實現的是來自prepareInstall ,我想直接返回event.args所以我會像這樣使用它:

const { sender } = await prepareInstall();

但是返回event.args並不能解決它,因為run中的typescript仍然需要我做: event.args.sender 重要的是我需要在prepareInstall中返回typeInstallationPreparedEvent因為在run中,我想要 typescript 告訴我存在哪些值(發件人,權限)。

希望我說得有道理。

如果我理解正確,您只想從InstallationPreparedEvent返回arg道具,但輸入正確(對嗎?)。

您可以通過括號表示法指定道具的類型:

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

這樣,您將獲得類型提示:

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; }'
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM