I'm trying to make type-safe handlers for redux actions relying on action type. For example, any action could be described as:
type ActionType<T extends string> = {
type: T
};
For a specific action one can have:
type MyAction = ActionType<'hey' | 'there'>;
Now, I'd like to restrict a handler function to allow only 'hey' or 'there' as a type. Finally I expect something like this:
handleAction<MyAction>('hey');
where the definition of the handler function could be:
function handleAction<A extends ActionType<T>>(type: T){
...
}
But I have a typescript compiler error:
TS2304: Cannot find name 'T'.
So, I have to modify this handler function definition in this way:
function handleAction<A extends ActionType<T>, T extends string>(type: T){
...
}
It works, but looks really ugly:
handleAction<MyAction, 'hey' | 'there'>('hey');
What's a better way to handle this?