繁体   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