【问题标题】:Is it possible to have a class extend number?是否可以有一个类扩展号?
【发布时间】:2015-01-18 23:06:26
【问题描述】:

我知道这可能是否定的,但打字稿中有什么方法可以让一个类从一个数字继承吗?我有一堆案例,其中类是一个数值和一堆方法。所以理论上这个类可以是一个数字加上那些方法。

有没有办法做到这一点?

谢谢 - 戴夫

【问题讨论】:

标签: typescript


【解决方案1】:

今天,这是可能的。

/**
 * Decimal class
 *
 * Represents a decimal number with a fixed precision which can be defined in the constructor.
 *
 * @export
 * @class Decimal
 * @extends {Number}
 * @implements {Number}
 */
export class Decimal extends Number implements Number {
  public precision: number;

  /**
   * Creates an instance of Decimal.
   *
   * @param {(number | string)} value
   *
   * @memberOf Decimal
   */
  constructor(value: number | string, precision: number = 2) {
    if (typeof value === 'string') {
      value = parseFloat(value);
    }

    if (typeof value !== 'number' || isNaN(value)) {
      throw new Error('Decimal constructor requires a number or the string representation of a number.');
    }

    super(parseFloat((value || 0).toFixed(2)));
    this.precision = precision;
  }

  /**
   * Returns the value of this instance as a number
   *
   * @returns {number}
   *
   * @memberOf Decimal
   */
  public valueOf(): number {
    return parseFloat(this.toFixed(2));
  }

  /**
   * Returns the string representation for this instance.
   *
   * @returns {string}
   *
   * @memberOf Decimal
   */
  public toString(): string {
    return this.toFixed(2);
  }
}

【讨论】:

  • 在TS里,我可以const a: Number = 2。我相信我知道答案,但想验证一下,是否有任何黑客可以像const b: Decimal = 3 一样使用上述十进制?
【解决方案2】:

简短的回答是否定的。让我在 Stack Overflow 上发布答案所需的长答案也是否定的。

【讨论】:

  • 这让我笑了(长答案部分)。
  • 在下面查看我的答案
猜你喜欢
  • 2010-12-05
  • 2020-03-02
  • 2012-08-05
  • 2020-08-01
  • 2016-03-11
  • 1970-01-01
  • 1970-01-01
  • 2017-09-11
相关资源
最近更新 更多