【问题标题】:Creating Typescript Interface for Function that Accepts Other Functions as Parameters为接受其他函数作为参数的函数创建 Typescript 接口
【发布时间】:2016-10-29 08:12:36
【问题描述】:

我有一个案例,我将 resolve 和 reject Promise 函数作为委托传递给另一个函数:

//The function
someFunc(x, y, resolve, reject);

但是我无法以不会引发以下错误的方式创建我的界面:

Argument of type '(value?: {} | PromiseLike<{}>) => void' is not assignable to parameter of type '(reason?: any) => Promise<void>'.

类型“void”不可分配给类型“Promise”。

我的界面目前如下:

someFunc(prop1: string, prop2: string, callingFunctionResolve?: Promise<void>, callingFunctionReject?: Promise<void>);

我也尝试过,但收到不同的错误:

callingFunctionResolve(reason: any)?: Promise<void>, callingFunctionReject(reason?: any)?: Promise<void>)

 A parameter initializer is only allowed in a function or constructor implementation.

Typescript 目前有没有一种方法可以以这种方式使用委托?我已经看到了一些建议,但还没有遇到任何有效的或这种确切类型的用例。

【问题讨论】:

    标签: typescript


    【解决方案1】:

    您可以检查lib.es6.d.ts 文件以找出解析/拒绝函数的签名。
    它们在PromiseConstructor中定义:

    interface PromiseConstructor {
        ...
    
        new <T>(executor: (resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) => void): Promise<T>;
    
        ...
    }
    

    所以你的功能应该是:

    function someFunc(
        prop1: string,
        prop2: string,
        callingFunctionResolve?: (value?: void | PromiseLike<void>) => void,
        callingFunctionReject?: (reason?: any) => void) { }
    

    然后你可以:

    new Promise<void>((resolve, reject) => {
        someFunc("str1", "str2", resolve, reject);
    });
    

    (code in playground)

    【讨论】:

      猜你喜欢
      • 2023-01-30
      • 2019-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 2022-01-09
      相关资源
      最近更新 更多