我有一个像这样的 redux 状态
interface DataState {
dashboard: {
data: DashboardData | null
isLoading: boolean
error: string | null
}
policySearch: {
data: PolicySearchData | null
isLoading: boolean
error: string | null
}
other: {
someKey: someValue
}
}
我有一个动作创建者,可以isLoading
在数据状态的给定字段中切换状态
toggleDataLoading('policySearch', true)
我不想发送错误的第一个参数来toggleDataLoading
运行,所以我有这个:
type FieldsThatHaveLoadingState = 'dashboard' | 'policySearch
因为有些字段没有isLoading
状态
我试图想出一种以编程方式从DataState
with Typescript收集密钥的方法。在javascript中看起来像这样:
const keysIWant = {}
Object.keys(dataState).forEach(key => {
if(dataState[key].isLoading) keysIWant[key] = true
})
type FieldsThatHaveLoadingState = keyof typeof keysIWant
是否可以仅使用 Typescript 类型和检查来进行这种集合?
下面显示的方法正确地将有效键限制为函数调用。
必须使用嵌套的分布式条件来表达这一点的复杂性有望随着https://github.com/microsoft/TypeScript/issues/23188上的工作而消失
interface DataState {
dashboard: {
isLoading: boolean
}
policySearch: {
isLoading: boolean
}
other: {
someKey: 'someValue'
}
}
type LoadableKey<T = keyof DataState> = T extends keyof DataState ? DataState[T] extends { isLoading: boolean } ? T : never : never
const toggleDataLoading = (stateKey: LoadableKey) => {
console.log(`Loading ${stateKey}`)
}
toggleDataLoading('dashboard');
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句