是否可以有一个类扩展号?

时间:2014-11-20 22:13:27

标签: typescript

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

有办法做到这一点吗?

谢谢 - 戴夫

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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);
  }
}