我试图在打字薄3应用程序中使用big.js和toFormat。正如在GitHub页面中所解释的,我已经安装了来自DefinitelyTyped项目的类型:
npm install big.js
npm install toformat
npm install --save-dev @types/big.js但是,toFormat没有类型定义;所以我编写了自己的:
// toformat.d.ts
declare module 'toformat' {
import type { BigConstructor, Big, BigSource } from 'big.js';
export interface Decimal extends Big {
toFormat(dp: number, rm?: number, fmt?: Object): string;
}
export interface DecimalConstructor extends BigConstructor {
new (value: BigSource): Decimal;
}
export default function toFormat(ctor: BigConstructor): DecimalConstructor;
}现在,我可以像下面这样使用big.js和toFormat (这很有效):
import toFormat from 'toformat';
import Big from 'big.js';
const Decimal = toFormat(Big);
console.log(new Decimal(12500.235).toFormat(2));但是,与其每次使用时执行toFormat,不如使用以下更简单的语法:
import Decimal from '../utilities/decimal'; // both type and value are imported here
let amount: Decimal;
amount = new Decimal(23.152);
console.log(amount.toFormat(2));为此,我创建了/实用程序/十进制文件:
import Big from 'big.js';
import toFormat from 'toformat';
export type { Decimal } from 'toformat';
export default toFormat(Big);现在的问题是,import Decimal from '../utilities/decimal';确实导入了DecimalConstructor,但没有导入Decimal接口。我看到import Big from 'big.js';同时导入了BigConstructor和BigConstructor;因此,似乎可以将我的Decimal接口和DecimalConstructor放在同一个Decimal名称下。有人能帮我吗?
更新:顺便说一下,以下工作:
import type { Decimal } from '../utilities/decimal';
import DecimalConstructor from '../utilities/decimal';
let amount: Decimal;
amount = new DecimalConstructor(23.152);
console.log(amount.toFormat(2));我喜欢实现的是以默认导入的相同名称导入Decimal和DecimalConstructor。
发布于 2022-02-22 14:26:51
经过一些试验和错误之后,我使它以下列方式工作:
// /utilities/decimal.ts
import Big from 'big.js';
import toFormat from 'toformat';
import type { Decimal as Dec } from 'toformat';
const Constructor = toFormat(Big);
export const Decimal = Constructor;
// 'export default from' is not possible.
// See https://github.com/microsoft/TypeScript/issues/35010
// and https://github.com/tc39/proposal-export-default-from
export interface Decimal extends Dec { }
export default Decimal;理想情况下,我不想重新声明十进制接口,但我找不到更好的方法。
https://stackoverflow.com/questions/71220984
复制相似问题