javascript - 打字稿用函数创建自己的类型
问题描述
我正在尝试创建自己的类型,我可以使用dot syntax
.
例如:
let myOwnType: myByteType = 123211345;
myOwnType.toHumanReadable(2);
我想归档相同的行为,如数字、数组等。我不想使用调用签名或构造函数签名创建我的类型
所以在查看了打字稿库后,我看到了这个数字界面:
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..
}
我如何创建自己的类型并像普通类型一样使用它们?我知道界面也不起作用,但这是我的第一个猜测。
解决方案
问题是我找不到函数体的定义位置和方式。
它们由 JavaScript 引擎定义,作为标准库的一部分。您会在 上找到它们Number.prototype
。它是这样工作的:当你试图访问一个基元(例如)的属性时,JavaScript 引擎会在该基元的对象类型(number => 、 string =>等)someNumber.toString()
的原型上查找该属性。如果您正在进行调用,它会调用该方法,传入原语(在严格模式下)或原语的对象包装器(在松散模式下)。Number
String
您无法定义自己的原始类型,这只能在 JavaScript 规范级别完成。
您可以创建一个Byte
类并拥有它的实例,但它们将是对象,而不是原语。
class Byte {
constructor(public value: number) {
}
yourMethodHere() {
// ...
}
}
您也可以向 中添加方法Number.prototype
,但最好不要在您可能与他人共享的任何库代码中这样做。(在您自己的应用程序或页面中,它几乎没问题,只要确保使用标准库的未来功能不太可能使用的名称。)
例如,这toHex
为数字添加了一个方法:
// Adding it to the type
interface Number {
toHex(): string;
}
// Adding the implementation
Object.defineProperty(Number.prototype, "toHex", {
value() {
return this.toString(16);
},
enumerable: false, // This is the default, but just for emphasis...
writable: true,
configurable: true
});
推荐阅读
- android - 不知道如何在服务类上从 layoutt 上的 seekbar 获得浮动。安卓工作室
- javascript - 刷新后保持程序状态
- python - 更新python类的状态
- java - JavaFX:从 Vbox 中删除一个孩子
- python - 将列表写入 2 个不同的文本文件
- sql - 有没有办法同时查询别名和分区?
- python - 使用 scipy.spatial.cKDTree 或 queryBallPoint 与随机 2d 点使用两个数据集之间的最近邻居时出现问题
- nlp - 在 HuggingFace 库中基于 BERT 的模型中,merge.txt 文件是什么意思?
- solr - solr 突出显示:重叠的 html 标签
- python - 当我的角色静止不动时,我的敌人没有移动