Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import all classes in one file and use them from there typescript

For example, I have a class A.ts

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

and class B.ts

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

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

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

then I want to import all of them in ONE file 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 will contain only imports/exports, no class implementation or any other code. And then my problem: I want to use A and B classes in app.ts calling them over Headers.ts file.

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

how to do this?

like image 632
Zack Zilic Avatar asked Dec 18 '22 05:12

Zack Zilic


2 Answers

OK I found the solution: in the file Headers.ts I need only to export classes:

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

and then to use class B, I need to import Headers.ts in app.ts file:

import * as headers from './HEADERS_path';

then I gonna make an instance of B class and call it's methods easily:

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"*
like image 115
Zack Zilic Avatar answered Feb 23 '23 01:02

Zack Zilic


You have to export all classes in Headers.ts

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

If you have multiple classes in A_path for example you can do:

export * from "../A_path";

Note that you can't use export * from with default exports.

You can read more about import/export on MDN.

like image 45
XCS Avatar answered Feb 23 '23 01:02

XCS