面试题答案
一键面试实现原理
- Actions 类型生成:
- 使用映射类型遍历状态接口的每个属性。
- 对于每个属性,根据其类型生成对应的 action 函数类型。例如,对于
count
属性,生成increment
函数类型,对于布尔类型的isLoading
,生成setLoading
函数类型。
- Selectors 类型生成:
- 同样使用映射类型遍历状态接口的每个属性。
- 生成的 selector 函数类型接收状态作为参数并返回对应属性的值。
代码实现
// 状态接口示例
interface State {
count: number;
isLoading: boolean;
}
// 生成 Actions 类型
type ActionTypes<S> = {
[K in keyof S as `set${Capitalize<string & K>}`]: S[K] extends boolean
? (value: boolean) => void
: S[K] extends number
? (value: number) => void
: never;
} & {
[K in keyof S as K extends 'count' ? 'increment' : never]: () => void;
};
// 生成 Selectors 类型
type SelectorTypes<S> = {
[K in keyof S]: (state: S) => S[K];
};
// 示例使用
const actions: ActionTypes<State> = {
setCount: (value) => {
// 实际实现中这里会更新状态
},
setLoading: (value) => {
// 实际实现中这里会更新状态
},
increment: () => {
// 实际实现中这里会更新状态
}
};
const selectors: SelectorTypes<State> = {
count: (state) => state.count,
isLoading: (state) => state.isLoading
};
这样,ActionTypes<State>
会生成符合 State
接口结构的 actions 类型,SelectorTypes<State>
会生成符合 State
接口结构的 selectors 类型。在实际使用中,可根据业务逻辑在 action 和 selector 函数中实现真正的状态更新和取值逻辑。