我正试图在typescript svelte 3应用程序中使用big.js和toFormat。正如GitHub页面上所解释的,我已经安装了来自确定性类型项目的类型:
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));
为此,我创建了/putilities/decimal.ts文件:
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';
同时导入Big接口和BigConstructor;因此,似乎可以将Decimal接口和DecimalConstructor放在同一个Decimal
名称下。有人能帮我吗?
更新:BTW,以下作品:
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都导入到与默认导入相同的名称下。
经过一番尝试和错误之后,我使其按以下方式工作:
// /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;
理想情况下,我不想重新声明Decimal接口,但我找不到更好的方法。