比如我有一个类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 中使用 A
和 B
类调用它们 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/