在这个示例中,我创建了两个类型化的对象,toggle和counter,它们都符合Config接口,每个对象都传递自己的State和Action参数类型。
我的问题是,如何在我的Config函数体中访问这些State类型及其相关的State和Action参数?我不知道如何输入这个论点,这样我就不会丢失那些信息?
我已经阅读了TS文档,我认为这是泛型可能有帮助的东西吗?
发布于 2019-07-29 10:43:52
我找到了这篇文章,它解释了如何从类型中提取param值。
https://itnext.io/typescript-extract-unpack-a-type-from-a-generic-baca7af14e51
这使用了条件类型,基本语法如下:
type ExtractState<C> = C extends Config<infer State, infer Action> ? State : never;
发布于 2019-07-26 10:41:21
如果我理解正确的话..。您可以这样指定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>
})
// ....
}然而,困难在于您不知道State和Actions对于obj的每个属性的类型是什么,但至少您知道它符合Config接口。
https://stackoverflow.com/questions/57218238
复制相似问题