![](/img/trans.png)
[英]Typescript mapped types - enum value as key, and interface's corresponding value as value
[英]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
將導致M
在RouteMethodValidator
具有類型string
,因為Route<any>['methods']
是any
而keyof any
是string
。
現在,更改默認值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.