Sam Washburn Sam Washburn - 1 year ago 79
TypeScript Question

TypeScript class in traditional folder hierarchy

I'm a seasoned Java dev who needs to port a Java app for web use and I've been considering using Typescript to do this. For the time being, I'd like to keep the traditional Java style of packages being a hierarchy of folders and a single class per "leaf" file.

I've been looking at the Typescript docs and I see things like

. Are all includes relative like that? Is there some kind of base directory option where I can get something akin to

Also, is declaring a
something to be done in Typescript?

I've looked over the docs but I'm not finding them easy to read with all the talk about internal and external namespaces and exporting, etc.

Can someone boil this down to something that'll feel like Java for me to start out with? I'm sure I'll baby step into all the complex stuff later as needed. What does this look like in code?

Answer Source

Organizing your typescript classes into 1-class per file and an organized folder hierarchy is perfectly acceptable and even encouraged in typescript.

If using typescript 2.0 or above your paths do not need to be relative. You can use the baseUrl: property to specify where non-relative (i.e. no . or ..) paths are rooted. For example of you had:


you could set "baseUrl": "./src" and then you could import 'foo/foo' and import 'bar/bar' without using relative path navigation.

I would discourage you from trying to declare packages/namespace/internal modules and the like in typescript. These types of things are mostly relics of the past, and not something I would venture to use in a new project.

What I would recommend is to stick to file-based modules, as this is the modern recommended approach for composing your application.

A file that has import or export statements is considered a "file module". Everything defined within it is private to the file and does not pollute the global namespace. Things that should be shared need to be exported and imported from other files.

For example you could write the MyType class in a file structure like this:


my-type.ts Would look like:

export class MyType{
        console.log('Hello World');

and then you could import it in other files like:

import {MyType} from 'com/ancient/my-type'

You should not need to use the keywords namespace or module. These are mostly things that will only be found in type declaration files.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download