My previous question from three weeks ago has led to this extension: Set the keys of an interface to the possible values of a different interface?
In summary, I have the following type definitions:
interface SuccessStatus {
type: 'success';
payload: string;
}
interface LoadingStatus {
type: 'loading';
}
interface ErrorStatus {
type: 'error';
error: string;
}
type RequestStatus = SuccessStatus | LoadingStatus | ErrorStatus;
And I have created a mapped Record type to define an object that handles each of the above statuses:
type RequestHandlerVisitor = Record<
RequestStatus["type"],
(status: RequestStatus) => void
>;
With each T
having a corresponding K
function.
This results in an object like this:
const statusVisitor: RequestHandlerVisitor = {
"success": (status: RequestStatus) => { ... },
"loading": (status: RequestStatus) => { ... },
"error": (status: RequestStatus) => { ... },
}
Now, I am looking to create a similar type where the value of K
changes based on the key T
, such as:
const statusVisitor: NewRequestHandlerVisitor = {
"success": (status: SuccessStatus) => { ... },
"loading": (status: LoadingStatus) => { ... },
"error": (status: ErrorStatus) => { ... },
}
In this case, the first argument of function K
will vary based on T
.
One potential solution is to hardcode the type like this:
interface NewRequestHandlerVisitor {
"success": (status: SuccessStatus) => void;
"loading": (status: LoadingStatus) => void;
"error": (status: ErrorStatus) => void;
}
While this works for now, it may become cumbersome when dealing with more "Status" types, as each would require a new entry in the type.
Is there a way to dynamically define this?
Thank you!