【问题标题】:Typescript - How to use an interface in a callback functionTypescript - 如何在回调函数中使用接口
【发布时间】:2019-05-29 00:48:34
【问题描述】:

最近开始使用 Typescript 和一些我不确定的东西。

我正在使用一个 npm 包 azure-storage 并专门调用一个方法 doesBlobExist

blobService.doesBlobExist(containerName, blobName, (callbackResult: ErrorOrResult<BlobService.BlobResult>) => {
        //Want callbackResult.response here
});

doesBlobExist(来自 npm 包的函数)看起来像这样:

doesBlobExist(container: string, blob: string, callback: ErrorOrResult<BlobService.BlobResult>): void;

ErrorOrResult 类型是一个具有这个的接口:

interface ErrorOrResult<TResult> {
    (error: Error, result: TResult, response: ServiceResponse): void
}

我不确定我在哪里调用该函数,我希望我可以使用该接口并执行以下操作:

callbackResult.response 在界面中,但callbackResult 一直返回为null。 在查看它时,它被设置为界面中的error: Error

那么实际上是否可以做我想要做的事情,或者我必须像这样使用那个功能:

blobService.doesBlobExist(containerName, blobName, (error, result, response) => {
        //i.e. specify the 3 items directly in the interface
});

【问题讨论】:

    标签: typescript interface callback


    【解决方案1】:

    阅读你的问题,你可以使用你上面写的解决方案,你可以做类似的事情:

    blobService.doesBlobExist(containerName, blobName, (error, result, response) => {
            if(error !== null){
               // Do something
               return;
            } 
            // here you can work with your response data
    });
    

    如果您想避免该错误,您可以省略 if 循环,并直接处理您的响应,但您必须在响应中插入所有可能的选项。

    callbackResult.response 在接口中,但是 callbackResult 一直返回为 null。在查看它时,它被设置为错误:来自接口的错误。

    正如你所说,你得到一个 null 因为函数没有返回错误。

    【讨论】:

      猜你喜欢
      • 2021-10-26
      • 2021-11-10
      • 2017-12-18
      • 2019-09-27
      • 2011-10-08
      • 1970-01-01
      • 2019-07-08
      • 2018-03-21
      • 2023-02-21
      相关资源
      最近更新 更多