0
我知道这可能是一个不,但是有没有在打字稿中有一些方法来从一个数字继承一个类?我有一堆案例,其中类是一个数值和一堆方法。所以理论上这个类可以是一个数字加上这些方法。是否可以有一个类扩展号码?
有没有办法做到这一点?
谢谢 - 戴夫
我知道这可能是一个不,但是有没有在打字稿中有一些方法来从一个数字继承一个类?我有一堆案例,其中类是一个数值和一堆方法。所以理论上这个类可以是一个数字加上这些方法。是否可以有一个类扩展号码?
有没有办法做到这一点?
谢谢 - 戴夫
简短的回答是没有。需要让我发布堆栈溢出的答案的长答案也不是。
今天,这是可能的。
/**
* 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);
}
}
这让我发笑(长答案部分)。 – 2014-11-21 00:32:22
请在下面查看我的答案 – svallory 2017-09-07 11:41:56