简体   繁体   中英

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

In this example i have created 2 typed objects, toggle and counter which both conform to the Config interface, each passing their own State and Action parameter types.

My question is, how can i access these Config types and their associated State and Action params inside my createStore function body? I have no idea how to type the argument so that i don't lose that information?

I have read through the TS docs and im thinking this is something generics might help with?

If I've understood correctly... you can specify the types for toggle and counter like this -

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

And then you can inline the obj parameter for your function -

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

Edit after comments: Something like this may help, too, if you don't always have a toggle and a counter property (ie the properties of obj are arbitrary) -

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

    // ....
}

The difficulty though is that you won't know what the types are for State and Actions for each property of obj - but at least you know it conforms to a Config interface.

I found this article which explains how to go about extracting param values from a type.

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

This makes use of conditional types, the basic syntax is as follows:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM