Redux Toolkit切片中Omit类型意外包含原型键问题求解
问题原因与解决方案
核心问题1:类型定义笔误
你对ContestFilterKey的定义存在递归引用错误:
// 错误写法:递归引用了自身 type ContestFilterKey = keyof ContestFilterKey;
你实际想要的是取ContestFilterSliceType的键集合,正确定义应为:
type ContestFilterKey = keyof ContestFilterSliceType;
核心问题2:工具类型使用错误
Omit是用于对象类型的工具类型,作用是从传入的对象类型中移除指定键,返回新的对象类型。你传入的ContestFilterKey是字符串字面量联合类型,而非对象类型,TS会将联合类型自动推断为带所有字符串原型属性的对象类型,因此会带出toString、concat等原型方法键。
要从联合类型中排除指定成员,需要使用Exclude工具类型。
修正后的完整代码
const initialState = { gameModes: [] as string[], contestTypes: [] as string[], entryFee: { max: 10000, min: 0, }, entryTypes: [] as string[], advancedFilters: [] as string[], }; type ContestFilterSliceType = typeof initialState; // 修正:取slice类型的键 type ContestFilterKey = keyof ContestFilterSliceType; const contestFilterSlice = createSlice({ name: "constestFilter", initialState, reducers: { addFilter( state, // 修正:用Exclude从联合类型中排除entryFee action: PayloadAction<{ key: Exclude<ContestFilterKey, "entryFee">; filter: string }> ) { const { filter, key } = action.payload; state[key].push(filter); }, }, });
修正后key的类型就会是你预期的"gameModes" | "contestTypes" | "entryTypes" | "advancedFilters"联合类型。
内容的提问来源于stack exchange,提问作者Jonathan Tuzman
相关产品推荐
相关产品推荐

