【发布时间】:2018-03-01 08:21:15
【问题描述】:
我有一个 http 方法的枚举:
export enum HttpMethod {
GET = 'GET', POST = 'POST', /*...*/
}
然后我定义一个基本的方法类型,它可以有任何HttpMethod 作为键:
type Methods = {
[M in HttpMethod]?: any;
};
一个基本的 Route 类型可以使用这个 Method 类型:
type Route<M extends Methods = any> = {
methods: M;
}
所以我可以定义任何路线,例如:
interface AnyRoute extends Route<{
[HttpMethod.GET]: AnyRequestHandler;
}> {}
到目前为止一切顺利。现在我想添加一个Validator:
type Validator<R extends Route, M extends HttpMethod> = {/*...*/}
并且只想允许将Methods 添加到Validator,这是在Route 中定义的:
type RouteMethodValidators<R extends Route> = {
[M in keyof R['methods']]?: Validator<R, M>;
};
虽然我的 IDE 似乎理解它,但我收到以下错误:
-
Type 'M' does not satisfy the constrain 'HttpMethod'. Type 'keyof R["methods"]' is not assignable to type 'HttpMethod'.
有什么方法可以告诉 typescript,这绝对是HttpMethod 的成员?
【问题讨论】:
标签: typescript generics enums definition