【问题标题】:How to set function-type in interface, rather than setting function's return type如何在接口中设置函数类型,而不是设置函数的返回类型
【发布时间】:2020-06-05 14:38:11
【问题描述】:

我正在尝试定义一个带有可调用字段的接口,如下所示:

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 的对象。我想要的是为该可调用函数设置类型,而不是为该函数设置返回类型。

我可以通过

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,因为我想在其他地方重用该类型。

谢谢!

【问题讨论】:

  • 我不明白你在问什么????。 this 对你来说还不够好吗?你能详细说明吗?祝你好运!
  • @jcalz 与您所做的基本相似。在您的情况下,您定义了函数的返回类型。我想要的是定义函数的类型,而不是返回类型。希望对您有所帮助。
  • (arg: P): MyFnType&lt;P, R, T&gt; 返回一个函数。你要(arg: P): ReturnType&lt;MyFnType&lt;P, R, T&gt;&gt;;吗?
  • 啊,是的,行了!所以我想除了使用ReturnType&lt;...&gt;之外没有其他方法可以设置返回类型?
  • 我不明白您对另一种设置返回类型的方式可能意味着什么。也许你想要type PayloadActionCreatorWithFnType&lt;P = void, R = void, T extends string = string&gt; = MyFnType&lt;"this param is unused?!", P, R&gt; &amp; { type: T }

标签: javascript typescript types


【解决方案1】:

我认为您可能只是在寻找 ReturnType&lt;T&gt; 实用程序类型:

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;

好的,希望对您有所帮助;祝你好运!

Playground link to code

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-31
    • 2020-04-05
    • 2021-04-01
    • 2023-02-15
    • 2018-07-12
    • 2012-01-14
    • 2016-04-05
    • 1970-01-01
    相关资源
    最近更新 更多