gpt4 book ai didi

typescript - 未强制执行字符串文字类型参数

转载 作者:搜寻专家 更新时间:2023-10-30 21:50:47 26 4
gpt4 key购买 nike

对于 Redux(虽然这个问题与 Redux 没有任何关系)我想知道 reducer 使用的 Action 的名称,但我想确保 reducer 中使用的名称和 Action 是一致的。所以我写了这段代码:

interface TypedAction<N> {
type: N;
}

type TypedReducer<S, A extends TypedAction<any>> = (state: S, action: A) => S;

function addReducer<S, R extends TypedReducer<S, A>, A extends TypedAction<N>, N>(initialState: S, actionName: N, reducer: R): {} {
// doesn't really matter what is returned here
// the point is I need the actionName during run time
// but want it to correspond with the reducer's action's name at compile time
return {
[actionName.toString()]: reducer
};
}

但是当我尝试一个例子时:

interface MyAction extends TypedAction<'MyAction'> {
foo: string;
}

const myActionReducer: TypedReducer<number, MyAction> = (state: number, action: MyAction) => state+1;

addReducer(1, "foo", myActionReducer); // should give a compile error, because "foo" and is not of type "MyAction"

为什么 Typescript 不强制 "foo" 应该是 "MyAction"

最佳答案

interface TypedAction<T extends string> {
type: T;
}

type TypedReducer<S, A extends TypedAction<any>> = (state: S, action: A) => S;

interface MyAction extends TypedAction<"MyAction"> {
foo: number;
}

type ActionTypeAndReducer<S, A extends TypedAction<any>> = {
[type: string]: TypedReducer<S, A>
};

function pair<ActionType extends string,
A extends TypedAction<ActionType>,
S>(type: ActionType, reducer: TypedReducer<S, A>): ActionTypeAndReducer<S, A> {
return {
[type as string]: reducer
};
}

const myReducer: TypedReducer<any, MyAction> = (state: any, action: MyAction) => {};
pair("MyAction2", myReducer);

这将产生预期的行为。

error TS2345: 
Argument of type 'TypedReducer<any, MyAction>' is not assignable to parameter
of type 'TypedReducer<any, TypedAction<"MyAction2">>'.

Types of parameters 'action' and 'action' are incompatible.
Type 'TypedAction<"MyAction2">' is not assignable to type 'MyAction'.
Property 'foo' is missing in type 'TypedAction<"MyAction2">'.

我认为结合了 action 和 reducer 的函数可以检查这一点,所以我构建了 pair 函数。 类型没问题,但编译器提示说 type argument 必须是 stringnumber 因为它是返回对象中的键。所以我让 ActionType 扩展字符串,然后剩下的就没问题了。

关于typescript - 未强制执行字符串文字类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45062128/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com