TypeScript扩展第三方模块时,如何同时导出常量与接口?
解决方案
要同时扩展TaskEither的功能并保留原模块的类型(包括TaskEither接口),需要分开处理值导出和类型导出——因为TypeScript中值和类型属于不同的命名空间。以下是具体实现方式:
实现代码
// 导入原模块的所有值 import * as ITE from "fp-ts/lib/TaskEither"; // 单独导入原模块的所有类型,避免值与类型混淆 import type * as TITE from "fp-ts/lib/TaskEither"; // 自定义扩展函数 const foo = () => "foo"; // 扩展原TaskEither的所有值,添加自定义函数 export const TE = { ...ITE, foo }; // 声明TE的命名空间,将原模块类型挂载到TE上 declare namespace TE { // 导出原模块的TaskEither接口 export type TaskEither = TITE.TaskEither; // 按需导出其他需要的类型,比如TaskEitherURI、LeftTask等 export type TaskEitherURI = TITE.TaskEitherURI; export type LeftTask<E, A> = TITE.LeftTask<E, A>; export type RightTask<E, A> = TITE.RightTask<E, A>; }
说明
- 值层面扩展:通过对象展开
...ITE保留原TaskEither的所有方法(如left、right、map等),同时添加自定义的foo函数,最终导出为TE值。 - 类型层面挂载:通过
declare namespace TE将原模块的类型(如TaskEither接口)挂载到导出的TE命名空间下,这样使用者导入TE后,既可以调用值方法,也能直接通过TE.TaskEither访问类型。
使用示例
在其他模块中导入后即可同时使用值和类型:
import { TE } from "your-tool-library"; // 使用类型 const exampleTE: TE.TaskEither<string, number> = TE.right(100); // 使用扩展方法 console.log(TE.foo()); // 输出 "foo" // 使用原模块方法 TE.map(exampleTE, num => num * 2);
内容的提问来源于stack exchange,提问作者Adam A
相关产品推荐
相关产品推荐

