I have created an enum to represent various HTTP methods:
export enum HttpMethod {
GET = 'GET', POST = 'POST', /*...*/
}
Next, I have established a basic method type which can utilize any HttpMethod
as a key:
type Methods = {
[M in HttpMethod]?: any;
};
A generic Route type could make use of this Method type structure:
type Route<M extends Methods = any> = {
methods: M;
}
This allows me to define routes like the following example:
interface AnyRoute extends Route<{
[HttpMethod.GET]: AnyRequestHandler;
}> {}
So far, everything seems to be working smoothly. However, my intention now is to incorporate a Validator
:
type Validator<R extends Route, M extends HttpMethod> = {/*...*/}
Moreover, I only want to permit the addition of Method
s to the Validator
that are explicitly defined within the Route
:
type RouteMethodValidators<R extends Route> = {
[M in keyof R['methods']]?: Validator<R, M>;
};
Despite indications from my IDE that it understands the code, I encounter the following errors:
Type 'M' does not satisfy the constrain 'HttpMethod'.
Type 'keyof R["methods"]' is not assignable to type 'HttpMethod'.
Is there a way for me to explicitly convey to typescript that these values are indeed members of HttpMethod
?