// a.ts
interface Config {
selector?: <T>(httpResponse: HttpResponse<T>) => unknown;
}
export function factory(options: Config): something {
// use options to return something
}
// another file b.ts
// I have a type for res only here(b.ts), and I want to use it to specialize type T
import { factory } from 'a.ts';
factory({
selector: res => res.data.data; // error: Property 'data' does not exist on type 'T'
});
我的问题是:如何在config对象文字中传递指定的类型,以便可以泛化类型T?
请factory
以通用的功能,我们可以通过的“T”factory
到Config
什么也是一个通用的对象。
从Config
接口开始,使其成为通用接口。
interface Config<T> { // Generically for whole interface
selector?: (httpResponse: HttpResponse<T>) => unknown;
}
接下来,factory
功能:
export function factory<T>(options: Config<T>): something { // return type is "T" or something ?
// use options to return something
}
我们将类型“ T”从传递factory
给Config
。
最后是一个例子:
b.ts
export type ApiResponse = {
data: {
username: string;
}
}
工厂用途
factory<ApiResponse>({
selector: res => res.data.data.username, // typehint for the `res`, I try with HttpResponse is AxiosResponse
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句