pm100
pm100

Reputation: 50110

convert namespace to module based typescript code

c# programmer here. I started work on a medium sized ts code base. Modelled off an existing c# codebase. I started out doing

namespace Foo
{
    export function x;
    export const y;
    export class C1{}
}

for things that map to static classes and functions in c# and and 'real' classes

Foo being in one file called Foo.js. To call things I just said Foo.x() in a different file.

All fine, but more reading leads me to 'dont use namespaces'. So time for a refactor

I just want to make sure that I am doing the correct conversion. So now I do

export class Foo
{
    public x(){};
    public static readonly  y;
    public class C1{}
}

That replacement for const seems a mouthful. And when I call things I have to go

import {Foo} from "./Foo";
Foo.x();

So is this correct? Optimal?

Note - I want to keep the calling code doing Foo.x(); var c = Bar.wibble; etc. Ie really separate out the namespace of different functional parts

Upvotes: 1

Views: 2751

Answers (1)

casieber
casieber

Reputation: 7542

Good news, you are making the conversion even harder on yourself than it needs to be. Instead of what you have written, try going for:

export function x() { /* ... */ }
export const y = /* ... */;
export class C1 { /* ... */ }

Then in your consuming files you can import only what you need:

import { x } from './Foo';
x();

Or if you want to continue to use it like a namespace you can:

import * as Foo from './Foo';
Foo.x();

In many cases you may be able to simply remove the wrapping namespace declaration and be done.

Upvotes: 4

Related Questions