打字稿:映射类型中的枚举键

问题描述 投票:3回答:1

我有一个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'.

有什么方法可以告诉打字稿,这绝对是HttpMethod的成员吗?

typescript generics enums definition
1个回答
4
投票

你的问题主要在于:type Route<M extends Methods = any>

首先,默认值any将导致Mstring中的RouteMethodValidator类型,因为Route<any>['methods']anykeyof anystring

现在,将默认值更改为Methods仍然无法解决问题,因为你执行M extends Methods这基本上意味着M可以拥有比Methods中定义的更多的键,即比HttpMethods中定义的更多。但在Validator你只允许HttpMethods的值。

我相信你最好的选择是让Route不通用。

type Route = {
  methods: Methods;
}

type RouteMethodValidators<R extends Route> = {
  [M in HttpMethod]?: Validator<R, M>;
}
© www.soinside.com 2019 - 2024. All rights reserved.