You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 17:39:03