1

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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

5 Comments

import * as Foo from './Foo' to really use it as a namespace.
i want to keep doing Foo.x not x in the calling code.
Updated answer to add in * as Foo syntax as well
this doesnt work well - so it seems. If I have 2 files both with function x in them they end up clashing
The only way there could be clashing is if you did import { x } from './foo'; import { x } from './bar'. You can always either import using * as format: import * as Foo from './foo'; import * as Bar from './bar', or you can alias the imports import { x as fooX } from './foo'; import { x as barX } from './bar'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.