node.js - 如何在一个文件中导入所有类并从那里使用它们 typescript

标签 node.js typescript

比如我有一个类A.ts

export class A(){
    public constructor() {}
    public method() : string {
         return "hello from A";
    }
}

和类 B.ts

export class B(){
    public constructor() {}

    public method() : string {
         return "hello from B";
    }

    public static methodStatic() : string {
        return "hello from static B";
    }
}

然后我想将它们全部导入到一个 Headers.ts 文件中

imports {A} from    "../A_path";
imports * as b from "../B_path";

//Or just to export it? Make it public.
export * from "../A_path";
export * from "../B_path";

Headers.ts 将仅包含imports/exports,不包含类实现或任何其他代码。 然后是我的问题:我想在 app.ts 中使用 AB 类调用它们 Headers.ts 文件。

import * as headers from './HEADERS_path';
headers.A.method();
headers.B.method();

如何做到这一点?

最佳答案

好的,我找到了解决方案: 在文件 Headers.ts 中,我只需要导出类:

export {A} from "../A_path";
export {B} from "../B_path";

然后要使用 B 类,我需要在 app.ts 文件中导入 Headers.ts:

import * as headers from './HEADERS_path';

然后我将创建一个 B 类的实例并轻松调用它的方法:

let bInstance : headers.B = new headers.B();
//concrete method
bInstance.method();
//output will be what is expected: *"hello from B"*

//static method
headers.B.methodStatic();
//output will be what is expected: *"hello from static B"*

关于node.js - 如何在一个文件中导入所有类并从那里使用它们 typescript ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45163283/

相关文章:

javascript - 访问服务器端 javascript 变量以使用客户端 javascript 进行操作

javascript - TypeScript:有条件地扩展 React 组件中的 Prop

node.js - NestJs - 类验证器未返回完整的验证错误对象

node.js - Express.js 和 Mongoose : access Object attribute name by the request parameter

node.js - 如何从 Lerna monorepo 中的包中加载包?

typescript - 类型 'setPrototypeOf' 上不存在属性 'ObjectConstructor'

node.js - 在使用 Typescript 的 Mocha 测试中使用 Mockery 有技巧吗?

node.js - 我正在尝试使用nodejs将图像存储在mongo gridfs中

javascript - 如何在mongodb中分配id值?

c++ - 无法使用 node-gyp (C++) 编译 STK (The Synthesis Toolkit)