簡體   English   中英

TypeScript:訪問函數體內的嵌套對象類型和相關參數類型?

[英]TypeScript: Access nested object types and associted param types inside function body?

在此示例中,我創建了2個類型化的對象, togglecounter ,它們均符合Config接口,每個都傳遞自己的StateAction參數類型。

我的問題是,如何在createStore函數主體中訪問這些Config類型及其關聯的StateAction參數? 我不知道如何鍵入參數,這樣我才不會丟失該信息?

我已經閱讀了TS文檔,並且我認為這對泛型可能會有所幫助?

如果我正確理解...,可以像這樣指定togglecounter的類型-

type ToggleType = typeof toggle;
type CounterType = typeof counter;

然后可以內聯函數的obj參數-

const createStore = (obj: { toggle: ToggleType, counter: CounterType  }) => {
    const { toggle, counter } = obj;
}

在注釋后編輯:如果您不總是具有togglecounter屬性(即obj的屬性是任意的),則類似的內容也可能會有所幫助-

type CreateStoreContext = {
    [key: string]: Config<any, any>
}

const createStore = (obj: CreateStoreContext) => {
    Object.keys(obj).forEach(key => {    // Key is a string
        const config = obj[key];         // config is a Config<any, any>
    })

    // ....
}

但是,困難在於您將不知道obj每個屬性的StateActions的類型是什么-但至少您知道它符合Config接口。

我發現本文解釋了如何從類型中提取參數值。

https://itnext.io/typescript-extract-unpack-a-type-from-a-generic-baca7af14e51

這利用了條件類型,基本語法如下:

type ExtractState<C> = C extends Config<infer State, infer Action> ? State : never;

暫無
暫無

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

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