【发布时间】:2020-06-13 10:12:45
【问题描述】:
我正在尝试创建自己的类型,我可以使用 dot syntax 在其上调用函数。
例如:
let myOwnType: myByteType = 123211345;
myOwnType.toHumanReadable(2);
我想归档相同的行为,例如数字、数组等。 我不想使用调用签名或构造函数签名来创建我的类型
所以在查看了 typescript 库后,我看到了这个数字界面:
interface Number {
/**
* Returns a string representation of an object.
* @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers.
*/
toString(radix?: number): string;
/**
* Returns a string representing a number in fixed-point notation.
* @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.
*/
toFixed(fractionDigits?: number): string;
/**
* Returns a string containing a number represented in exponential notation.
* @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive.
*/
toExponential(fractionDigits?: number): string;
/**
* Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits.
* @param precision Number of significant digits. Must be in the range 1 - 21, inclusive.
*/
toPrecision(precision?: number): string;
/** Returns the primitive value of the specified object. */
valueOf(): number;
}
问题是我找不到函数体的定义位置和方式。我在想一定有一个实现接口的类或类似的东西。
我想出了这样的尝试:
interface Bytes {
toHumanReadable(decimals: number): bytesToHumanReadable;
bytesAs(unit: string): string;
}
function bytesToHumanReadable (decimals: number) {
// convert bytes to GB, TB etc..
}
我如何创建自己的类型并像使用普通类型一样使用它们? 我知道接口也不起作用,但这是我的第一个猜测。
【问题讨论】:
-
您可能想使用
class,而不是interface(请参阅stackoverflow.com/a/55505227/2358409)
标签: javascript typescript types