[英]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.