【发布时间】:2015-01-18 23:06:26
【问题描述】:
我知道这可能是否定的,但打字稿中有什么方法可以让一个类从一个数字继承吗?我有一堆案例,其中类是一个数值和一堆方法。所以理论上这个类可以是一个数字加上那些方法。
有没有办法做到这一点?
谢谢 - 戴夫
【问题讨论】:
-
这里是一个智能、简洁的实现:stackoverflow.com/a/48061917/370878
标签: typescript
我知道这可能是否定的,但打字稿中有什么方法可以让一个类从一个数字继承吗?我有一堆案例,其中类是一个数值和一堆方法。所以理论上这个类可以是一个数字加上那些方法。
有没有办法做到这一点?
谢谢 - 戴夫
【问题讨论】:
标签: typescript
今天,这是可能的。
/**
* 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);
}
}
【讨论】:
const a: Number = 2。我相信我知道答案,但想验证一下,是否有任何黑客可以像const b: Decimal = 3 一样使用上述十进制?
简短的回答是否定的。让我在 Stack Overflow 上发布答案所需的长答案也是否定的。
【讨论】: