为特定方法创建重载方法时,现在调用它仅适用于第一个定义的重载。如果调用适用于第二个重载,它会引发错误,因为类型与第一个重载定义不对应。
我有一个AxiosWrapper
我创建的类,所以我可以添加一些重载方法。Axios 的泛型函数原型是最后一个。
export interface MeiliAxiosWrapperInterface {
post(
url: string,
data: IndexRequest,
): Promise<IndexResponse>
post<T = any, R = AxiosResponse<EnqueuedUpdate>>(
url: string,
data?: T,
): Promise<R>
}
// axios-wrapper.ts
import * as Types from './types'
class AxiosWrapper implements Types.MeiliAxiosWrapper {
post(
url: string,
data: Types.IndexRequest,
): Promise<Types.IndexResponse>
post<T = any, R = AxiosResponse<Types.EnqueuedUpdate>>(
url: string,
data?: T,
): Promise<R> {
return this.instance.post(url, data, config) // this.instance is an axios instance
}
}
这个实现很适合这个方法(这个方法所在的类扩展了 AxiosWrapper,所以 this.post 使用了 AxiosWrapper):
class Client extends AxiosWrapper {
//...
async createIndex(data: Types.IndexRequest): Promise<Indexes> {
const url = `/indexes`
const index = await this.post(url, data);
return new Indexes(this.config, index.uid)
}
}
在这种方法上,当我只使用默认的 axios 原型时,它曾经可以工作。但是现在我添加了一个重载它失败了:
class Indexes extends AxiosWrapper implements Types.Indexes {
//...
addDocuments(
documents: Types.Document[],
): Promise<Types.EnqueuedUpdate> {
const url = `/indexes/${this.indexUid}/documents`
return this.post(url, documents)
}
}
引发此错误:
Argument of type 'Document<any>[]' is not assignable to parameter of type 'IndexRequest'.
Property 'uid' is missing in type 'Document<any>[]' but required in type 'IndexRequest'.
我的错误是我没有添加不应用于比较而仅用于代码的最终重载。
export interface MeiliAxiosWrapperInterface {
post(
url: string,
data: IndexRequest,
): Promise<IndexResponse>
post<T = any, R = AxiosResponse<EnqueuedUpdate>>(
url: string,
data?: T,
): Promise<R>
}
// axios-wrapper.ts
import * as Types from './types'
class AxiosWrapper implements Types.MeiliAxiosWrapper {
post(
url: string,
data: Types.IndexRequest,
): Promise<Types.IndexResponse>
post<T = any, R = AxiosResponse<Types.EnqueuedUpdate>>(
url: string,
data?: T,
): Promise<R>
post(
url: string,
data?: any,
): Promise<any> {
return this.instance.post(url, data, config) // this.instance is an axios instance
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句