我有這個列舉,我的路由定義如下
export enum ApiPath {
User = "/users",
Property = "/properties",
...
}
例如,我在另一個類中使用我的介面 User 呼叫 GenericHttpClient。
如何將我的泛型型別與下面的列舉鍵匹配?
export class GenericHttpClient<T> extends HttpClient {
async findOne(args: { id: string }): Promise<T> {
const url = ApiPath[T]; // this is not working
return await this.get<T>(`${url}/${args.id}`);
}
}
'T' 僅指一種型別,但在這里用作值。
有沒有簡單的方法來解決這個問題?
uj5u.com熱心網友回復:
您不能T用作值,因為T它是一種型別,并且型別在運行時不存在。但是您可以使用T作為實體屬性存在的型別值。
此外,列舉并不是真正為您傳遞列舉鍵而設計的。而是接受MyEnum并傳入一個MyEnum.MyValue.
我假設您ApiPath使用GenericHttpClient.
這意味著你需要這樣做:
export class GenericHttpClient<T extends ApiPath> {
path: T
constructor(path: T) {
this.path = path
}
}
const client = new GenericHttpClient(ApiPath.User)
// client is of type: GenericHttpClient<typeof ApiPath['User']>
現在T由建構式的引數型別設定path,然后將該值保存到實體中。
現在您可以添加一個findOne()方法,這非常簡單:
async findOne(args: { id: string }): Promise<T> {
const url = this.path;
return await this.get<T>(`${url}/${args.id}`);
}
看游樂場
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/511338.html
標籤:反应打字稿仿制药
下一篇:C 泛型加法
