diff --git a/src/async.ts b/src/async.ts index 743f75fa..346f287b 100644 --- a/src/async.ts +++ b/src/async.ts @@ -1,14 +1,17 @@ import { coinTypeMap } from "./consts/coinTypeMap.js"; import type { + Coin, CoinName, CoinType, CoinTypeInvertedReference, Formats, } from "./types.js"; -export const getCoderByCoinNameAsync = async ( +export const getCoderByCoinNameAsync = async < + TCoinName extends CoinName | string = string +>( name: TCoinName -): Promise => { +): Promise => { const mod = await import(`./coin/${name}`); if (!mod) { throw new Error(`Unsupported coin: ${name}`); @@ -16,9 +19,13 @@ export const getCoderByCoinNameAsync = async ( return mod[name]; }; -export const getCoderByCoinTypeAsync = async ( +export const getCoderByCoinTypeAsync = async < + TCoinType extends CoinType | number = number +>( coinType: TCoinType -): Promise => { +): Promise< + TCoinType extends CoinType ? CoinTypeInvertedReference[TCoinType] : Coin +> => { const name = coinTypeMap[String(coinType) as keyof typeof coinTypeMap]; if (!name) { throw new Error(`Unsupported coin type: ${coinType}`); diff --git a/src/index.ts b/src/index.ts index 7d34ce93..609748d7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,32 +1,51 @@ import * as formats from "./coins.js"; import { coinTypeMap } from "./consts/coinTypeMap.js"; import type { + Coin, CoinName, CoinType, CoinTypeInvertedReference, + DecoderFunction, + EncoderFunction, Formats, } from "./types.js"; -export const getCoderByCoinName = ( +export type { + Coin, + CoinName, + CoinType, + CoinTypeInvertedReference, + DecoderFunction, + EncoderFunction, + Formats, +}; + +export const getCoderByCoinName = < + TCoinName extends CoinName | string = string +>( name: TCoinName -): Formats[TCoinName] => { - const format = formats[name]; +): TCoinName extends CoinName ? Formats[TCoinName] : Coin => { + const format = formats[name as keyof typeof formats]; if (!format) { throw new Error(`Unsupported coin: ${name}`); } - return format; + return format as TCoinName extends CoinName ? Formats[TCoinName] : Coin; }; -export const getCoderByCoinType = ( +export const getCoderByCoinType = < + TCoinType extends CoinType | number = number +>( coinType: TCoinType -): CoinTypeInvertedReference[TCoinType] => { +): TCoinType extends CoinType ? CoinTypeInvertedReference[TCoinType] : Coin => { const name = coinTypeMap[String(coinType) as keyof typeof coinTypeMap]; if (!name) { throw new Error(`Unsupported coin type: ${coinType}`); } - const format = formats[name] as CoinTypeInvertedReference[TCoinType]; + const format = formats[name]; if (!format) { throw new Error(`Unsupported coin type: ${coinType}`); } - return format; + return format as TCoinType extends CoinType + ? CoinTypeInvertedReference[TCoinType] + : Coin; };