如何在通用 createReducer 函数中强制执行更严格的 TypeScript 类型?

问题描述 投票:0回答:1

我有一个实用函数

createReducer
,它接受一个reducer函数并返回它:

const createReducer = <T>(reducer: (state: T, action: any) => T) => {
    return reducer;
};

type State = {
    foo: string;
};

createReducer<State>((state) => ({
    ...state,
    bar: 1 // How can I modify `createReducer` so TypeScript throws an error here?
}));

在上面的示例中,

createReducer
函数允许我向状态对象添加一个新的键(栏),即使它不是状态类型的一部分。

如果返回的状态具有状态类型中未定义的属性,我希望 TypeScript 给出错误。我怎样才能强制执行这种更严格的输入?

期望行为的示例:

type State = { foo: string };

// This should work
createReducer<State>((state) => ({
    ...state,
    foo: 'updated'
}));

// This should throw a TypeScript error because `bar` is not part of `State`
createReducer<State>((state) => ({
    ...state,
    bar: 1
}));

有没有办法修改

createReducer
或其类型来实现更严格的类型检查?

typescript generics type-safety
1个回答
0
投票

我唯一发现的是在创建内联对象时使用satisfies。 Ofc 这不是完美的解决方案,因为您可能会忘记添加它:

const createReducer = <T>(reducer: (state: T, action: any) => T) => {
    return reducer;
};

type State = {
    foo: string;
};

createReducer<State>((state) => ({
    ...state,
    bar: 1 // Error: Property 'bar' does not exist on type 'State'
} satisfies State));

© www.soinside.com 2019 - 2024. All rights reserved.