Estoy tratando de usar big.js con toFormat en la aplicación TypeScript Svelte 3. Como se explica en la página de GitHub, instalé tipos del proyecto DefinitelyTyped:
npm install big.js npm install toformat npm install --save-dev @types/big.jsPero no había definiciones de tipo para toFormat; así que escribí el mío:
// 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; }Ahora puedo usar big.js y toFormat como a continuación (que funciona):
import toFormat from 'toformat'; import Big from 'big.js'; const Decimal = toFormat(Big); console.log(new Decimal(12500.235).toFormat(2));Pero, en lugar de ejecutar toFormat cada vez que lo uso, me gustaría tener la siguiente sintaxis más simple:
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));Para eso creé el archivo /utilities/decimal.ts:
import Big from 'big.js'; import toFormat from 'toformat'; export type { Decimal } from 'toformat'; export default toFormat(Big); El problema ahora es que import Decimal from '../utilities/decimal'; importa DecimalConstructor, pero no la interfaz Decimal. Vi que import Big from 'big.js'; importa tanto Big interface como BigConstructor; por lo que parece posible poner mi interfaz Decimal y DecimalConstructor bajo el mismo nombre Decimal . ¿Puede alguien ayudarme con esto?
ACTUALIZACIÓN: Por cierto, los siguientes trabajos:
import type { Decimal } from '../utilities/decimal'; import DecimalConstructor from '../utilities/decimal'; let amount: Decimal; amount = new DecimalConstructor(23.152); console.log(amount.toFormat(2));Lo que me gustaría lograr es importar Decimal y DecimalConstructor con el mismo nombre que la importación predeterminada.
Después de algunas pruebas y errores, lo hice funcionar de la siguiente manera:
// /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;Idealmente, me gustaría no volver a declarar la interfaz Decimal, pero no pude encontrar una mejor manera.