TypeScript如何基于入参函数返回值自动推断createStore的返回类型
修改后的createStore实现
// 定义状态操作的Set、Get函数类型 type Setter<TState> = (updater: (state: TState) => void) => void type Getter<TState> = () => TState export const createStore = <TState extends Record<string, unknown>, TActions extends Record<string, unknown>>( document: TState, actions: (set: Setter<TState>, get: Getter<TState>) => TActions, ) => { // 内部状态管理逻辑可按实际需求完善 const state = { ...document } const set: Setter<TState> = (updater) => updater(state) const get: Getter<TState> = () => ({ ...state }) return Object.assign({}, state, actions(set, get)) as TState & TActions }
效果验证
// 测试场景1 const store = createStore( { value: false }, (set, get) => ({ changeValue: (newValue: boolean) => { set((state) => { state.value = newValue }) } }) ) // store 自动推断类型:{ value: boolean } & { changeValue: (newValue: boolean) => void }
// 测试场景2 const test = createStore({ hello: 'world' }, () => ({ update: () => 'test' })) // test 自动推断类型:{ hello: string } & { update: () => string }
核心改动说明
- 新增第二个泛型参数
TActions承接actions返回值的具体类型,替代原来的Record<string, unknown>避免类型丢失 - 关联Set、Get函数与状态类型
TState,保证内部操作的类型安全 - 返回值显式声明为初始状态与actions返回值的交叉类型,完成自动合并推断
内容的提问来源于stack exchange,提问作者Chris Drackett
相关产品推荐
相关产品推荐

