These are the current definitions I have on hand:
interface Action<T extends string, P> {
type: T;
payload: P;
}
type ActionDefinitions = {
setNumber: number;
setString: string;
}
type ActionCreator<A extends keyof ActionDefinitions> =
() => Action<A, ActionDefinitions[A]>;
The plan is to use ActionCreator<any>
, with any
being restricted to a key within ActionDefinitions
. This restriction is crucial when constructing a type like this:
type Creators = {
[K: string]: ActionCreator<keyof ActionDefinitions>
};
This requires automatic type deduction for each entry in the object. For instance, creating a Creators
object as follows:
const testCreators: Creators = {
foo: () => ({
type: "setNumber",
payload: "string",
})
}
An error should be triggered in this scenario because foo
needs to be inferred as an
ActionCreator<"setNumber">
, which means it must align with the type Action<"setNumber", number>
, indicating that the payload
should contain a number, not a string.
However, TypeScript simply permits any type for the payload
, which appears incorrect since if the generic type A
matches "setNumber," then foo
ought to return
Action<"setNumber", ActionDefinitions["setNumber"]>
, specifically Action<"setNumber", number>
...yet it accommodates any
instead of requiring number
.
Is there anyone aware of why this occurs or how it can be rectified?