【问题标题】:In TypeScript, how do I work out the proper type for 'this'?在 TypeScript 中,如何计算出“this”的正确类型?
【发布时间】:2021-05-20 19:11:22
【问题描述】:

目前,我的示例来自 Highcharts 库,但我问的是一般性问题,因为我想知道如何为任何库解决这个问题。

我的代码sn-p如下:

tooltip: {
            formatter: function () {
                return this.series.name + "," + this.point.y;
            }
        },

我想找出“this”的正确类型。

我从查看定义文件开始:

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/highcharts/index.d.ts

相关代码好像如下:

interface TooltipOptions extends SeriesTooltipOptions {

...

formatter?(): boolean | string;
...
}

在这里,我有点卡住了。我尝试将代码修改为:

tooltip: {
            formatter: function (this: Highcharts.TooltipOptions) {
                return this.series.name + "," + this.point.y;
            }
        },

但这不起作用。

我做错了什么以及如何计算出正确的类型?

【问题讨论】:

  • 有什么消息吗?解决方案?

标签: typescript highcharts


【解决方案1】:

Highcharts 导出您需要的类型。只需执行以下操作:

import Highcharts from 'highcharts`;

...

tooltip: {
  formatter(this: Highcharts.TooltipFormatterContextObject) {
    // your code
  }
}

【讨论】:

    【解决方案2】:

    幸运的是,this documentation comment 有一份保证存在于this 上的所有成员的列表。 (如果没有文档,您总是可以从您的函数中console.log(this) 并查看其中的内容。)本质上,您必须编写一个 TypeScript 接口来声明所有具有正确类型的成员:

    interface TooltipFormatterContext {
        percentage: number;  // Is this correct?
        // ...
    }
    

    然后将此接口用作您的this 类型。如果要正确表示共享工具提示和非共享工具提示,则需要两个类似于当前TooltipOptions 的不同接口,分别将shared 修复为falsetrue,并具有相应的this 类型对于格式化程序,然后您将 TooltipOptions 定义为两个接口的联合类型。

    【讨论】:

      【解决方案3】:

      用这些函数调用计算出 this 的类型的问题是第三方 api 可以绑定它想要的任何对象。

      tooltip.formatter.bind(someHighChartsObject);
      tooltip.formatter(); // this refers to someHighChartsObject
      tooltip.formatter.bind(someOtherHighChartsObject);
      tooltip.formatter(); // this refers to someOtherHighChartsObject
      

      在函数内部,指定 this 的类型有点困难,因为它可以是任何东西,包括文档中未定义的类型。在您的特定情况下,它应该是 Highcharts.PointObjectHighcharts.ChartObject 类型,您可以在技术上指定以下内容:

      const that: Highcharts.PointObject = this;
      that.series.name;
      

      问题:

      • 无法重新定义 this 的类型,因此您克隆该对象只是为了获得更强的输入。
      • 如果没有文档,或者他们使用未记录的类型,您必须检查 this 并编写自己的界面。

      TL;DR

      不可能在第三方代码调用的函数中简单地向 this 对象添加更强的类型。

      【讨论】:

        猜你喜欢
        • 2020-10-07
        • 2010-11-25
        • 2022-01-21
        • 2010-12-22
        • 2022-11-26
        • 2020-02-22
        • 2018-06-04
        • 2021-12-22
        相关资源
        最近更新 更多