我正在尝试定义一个具有可调用字段的接口,如下所示:
type MyFnType<P, R, T> = (arg: T) => Promise<R>;
declare interface PayloadActionCreatorWithFnType<P = void, R = void, T extends string = string> {
(arg: P): MyFnType<P, R, T>;
type: T;
}
我遇到的问题是上面定义了一个对象,该对象在调用obj()
时返回MyFunType
。我想要的是为该可调用函数设置TYPE,而不是为该函数设置返回类型。
我可以通过
实现相同的目的declare interface PayloadActionCreatorWithFnType<P = void, R = void, T extends string = string> {
(arg: P): Promise<R>;
type: T;
}
// Real application
const impl = (arg: string): Promise<string> => {
return new Promise(res => {});
};
impl.type = 'type';
const obj1: PayloadActionCreator<string, string, string> = impl; // no ts error
const obj2: PayloadActionCreatorWithFnType<string, string, string> = impl; // returns error
我想在上面的案例中使用FuncType,因为我想在其他地方重用该类型。
谢谢!
答案 0 :(得分:0)
我认为您可能只是在寻找ReturnType<T>
实用程序类型:
declare interface PayloadActionCreatorWithFnType<
P = void, R = void, T extends string = string> {
(arg: P): ReturnType<MyFnType<P, R, T>>;
type: T;
}
该实用程序类型是conditional type,用于提取函数类型的返回类型。像这样defined:
type ReturnType<T extends (...args: any) => any> =
T extends (...args: any) => infer R ? R : any;
好的,希望能有所帮助;祝你好运!