简体   繁体   English

使用BigNumber.toString时,使用TypeScript触发编译错误吗?

[英]Use TypeScript to trigger a compile error when BigNumber.toString is used?

Is it possible to use TypeScript to trigger a compile-time error if BigNumber.toString is called? 如果BigNumber.toString是否可以使用TypeScript触发编译时错误?

Specifically, my application has experienced bugs because BigNumber.toString() will express sufficiently large and sufficiently small numbers in scientific notation: 具体来说,我的应用程序遇到了bug,因为BigNumber.toString()将以科学计数法表示足够大和足够小的数字:

> x = new BigNumber('0.00000000001')
> x.toString()
'1e-10'
> x.toFixed()
'0.00000000001'

I've tried overriding the type: 我试过重写类型:

import {BigNumber} from "bignumber.js";

declare module "bignumber.js" {
  interface BigNumber {
    toString: never
    someOtherThing: number
  }
}

But this doesn't seem to work (and the someOtherThing field is added, so I know the type definitions are being loaded) 但这似乎不起作用(并且添加了someOtherThing字段,因此我知道正在加载类型定义)

How can I trigger a compile error if BigNumber.toString is used? 如果使用BigNumber.toString如何触发编译错误?

(also, note: I have set BigNumber.config({ EXPONENTIAL_AT: 1e+9 }) and overloaded BigNumber.toString so it issues a warning, but it would be nice to have the added compile error) (另请注意:我已经设置了BigNumber.config({ EXPONENTIAL_AT: 1e+9 })并重载了BigNumber.toString因此它发出了警告,但是最好添加附加的编译错误)

Is it possible to use TypeScript to trigger a compile-time error if BigNumber.toString is called 如果调用BigNumber.toString,是否可以使用TypeScript触发编译时错误?

Few options 很少的选择

Create a custom linter rule 创建自定义棉绒规则

Docs on tslint : https://palantir.github.io/tslint/develop/custom-rules/ You custom rule would be type checking rule : https://palantir.github.io/tslint/usage/type-checking/ tslint上的文档: https ://palantir.github.io/tslint/develop/custom-rules/您的自定义规则将是类型检查规则: https ://palantir.github.io/tslint/usage/type-checking/

And change toString invocations on BigNumber to be an error. 并将BigNumber上的toString调用更改为错误。

Edit the types on install 在安装时编辑类型

Remove the toString method from BigNumber by editing the installed .d.ts and commit it using PatchPackage : https://github.com/ds300/patch-package 通过编辑已安装的.d.ts从BigNumber中删除toString方法,并使用PatchPackage提交它: https : //github.com/ds300/patch-package

Create a wrapper 创建一个包装器

Alternatively create a wrapper around BigNumber that doesn't expose anything you consider dangerous to your fellow developers 🌹 或者,在BigNumber周围创建一个包装器,该包装器不会向开发人员暴露任何您认为危险的东西🌹

Thoughts 思考

I would personally use patch package as its the easier route. 我个人会使用补丁程序包作为更简单的方法。 If you are doing a lot of financial work with the library then consider a wrapper for your use case. 如果您要使用库进行大量财务工作,请考虑使用包装。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM