0

I'm working on a fairly small Typescript codebase that's gotten big enough to be split up across multiple files. It's a blackjack game. I currently have a bunch of code that looks like:

var player = new Player();
player.hand = new Hand([new Card(), new Card(), new Card()]);

in my main file, app.ts. For my sanity, I'd like to split the Player class off into one module and the Hand and Card off into a second. However, I'd like to keep Player, Card, and Hand all available in the top level scope for two reasons. First, to avoid things like:

var player = new Players.Player();
player.hand = new Cards.Hand([new Cards.Card(), new Cards.Card(), new Cards.Card()]);

and second, because I think it suggests a hierarchical relationship between Cards and Hand that I don't want to suggest. Cards contains stuff like Card, Deck, Hand, etc -- I think it's the sanest name choice (rather than something like CardCollections), but reading Cards.Hand makes me feel like Hand is-a Cards, which it isn't.

In Python, I would write:

from Cards import Card, Hand, Deck
from Players import Player

or

from Cards import *
from Players import *

The Typescript handbook suggests, essentially, that you make aliases for everything you need, but it looks to me like you still can't import anything into the top-level namespace.

Does this exist in Typescript?

Patrick Collins
  • 10,306
  • 5
  • 30
  • 69

2 Answers2

2

that you make aliases for everything you need, but it looks to me like you still can't import anything into the top-level namespace

Not the global global namespace but the top level namespace in a file, you do something like:

var Hand = Card.Hand; 
var Player = Players.Player;
basarat
  • 261,912
  • 58
  • 460
  • 511
1

Alternatively to @basarat answer, build your files as CommonJs modules using the --module commonjs flag on tsc and use the import...require syntax

To keep thing simple, have a single file per class

in Player.ts

class Player {


}
export = Player

in Hand.ts

class Hand {


}
export = Hand

in app.ts

import Hand = require('./Hand')
import Player = require('./Player')

var player = new Player()

Please note, no .ts extension in require

As an added benefit, you get easy access to the whole world of Node JS

Bruno Grieder
  • 28,128
  • 8
  • 69
  • 101