[英]TypeScript: Access nested object types and associted param types inside function body?
在此示例中,我創建了2個類型化的對象, toggle
和counter
,它們均符合Config
接口,每個都傳遞自己的State
和Action
參數類型。
我的問題是,如何在createStore
函數主體中訪問這些Config
類型及其關聯的State
和Action
參數? 我不知道如何鍵入參數,這樣我才不會丟失該信息?
我已經閱讀了TS文檔,並且我認為這對泛型可能會有所幫助?
如果我正確理解...,可以像這樣指定toggle
和counter
的類型-
type ToggleType = typeof toggle;
type CounterType = typeof counter;
然后可以內聯函數的obj
參數-
const createStore = (obj: { toggle: ToggleType, counter: CounterType }) => {
const { toggle, counter } = obj;
}
在注釋后編輯:如果您不總是具有toggle
和counter
屬性(即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
每個屬性的State
和Actions
的類型是什么-但至少您知道它符合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.