簡體   English   中英

打字稿:映射類型中的枚舉鍵

[英]Typescript: Enum Key in Mapped Types

我有一個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> = {/*...*/}

並且只想允許在Validator添加Method ,它們在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的成員嗎?

你的問題主要在於: type Route<M extends Methods = any>

首先,默認值any將導致MRouteMethodValidator具有類型string ,因為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>;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM