如何在Typescript中单独导出和导入类的成员方法
实现单独导入类中方法的解决方案
你当前定义的simpleMethod是类的实例方法,默认挂载在类的原型对象上,无法直接通过解构导入的方式单独引入。要实现你要求的import { simpleMethod } from '../../test.ts'导入写法,可以采用以下两种方案:
方案1:抽离方法单独导出,再挂载到类上
如果方法不需要依赖类实例上下文,可以直接把方法逻辑抽离成独立函数导出,再绑定到类上:
// test.ts 文件内容 import type { SomeStuff } from './your-type-path' // 单独导出方法 export async function simpleMethod(): Promise<any> { return { test: "test" } } export class Test { constructor( // 修正原拼写错误:readolny → readonly private readonly somStuff: SomeStuff ) {} // 将独立方法挂载为类的实例方法,需要用到实例上下文就加bind绑定 simpleMethod = simpleMethod.bind(this) }
之后就可以在其他文件直接按你想要的写法导入simpleMethod使用。
方案2:定义为静态方法后单独导出
如果该方法本身就是通用工具逻辑,不需要访问实例属性,可以直接定义为类的静态方法,再单独导出:
// test.ts 文件内容 import type { SomeStuff } from './your-type-path' export class Test { constructor( private readonly somStuff: SomeStuff ) {} // 定义为静态方法 static async simpleMethod(): Promise<any> { return { test: "test" } } } // 单独导出静态方法 export const simpleMethod = Test.simpleMethod
注意事项
- 如果你的
simpleMethod内部需要用到类实例的私有属性(比如somStuff),单独导出的方法没有实例上下文,无法正常运行,这种场景下不支持单独导入,必须先实例化Test类,再调用实例上的simpleMethod。 - 原代码中的
readolny为拼写错误,需修正为readonly。
内容的提问来源于stack exchange,提问作者markWanka
相关产品推荐
相关产品推荐

