简体   繁体   English

TypeScript:访问函数体内的嵌套对象类型和相关参数类型?

[英]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. 在此示例中,我创建了2个类型化的对象, togglecounter ,它们均符合Config接口,每个都传递自己的StateAction参数类型。

My question is, how can i access these Config types and their associated State and Action params inside my createStore function body? 我的问题是,如何在createStore函数主体中访问这些Config类型及其关联的StateAction参数? 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? 我已经阅读了TS文档,并且我认为这对泛型可能会有所帮助?

If I've understood correctly... you can specify the types for toggle and counter like this - 如果我正确理解...,可以像这样指定togglecounter的类型-

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

And then you can inline the obj parameter for your function - 然后可以内联函数的obj参数-

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) - 在注释后编辑:如果您不总是具有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>
    })

    // ....
}

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. 但是,困难在于您将不知道obj每个属性的StateActions的类型是什么-但至少您知道它符合Config接口。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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