How to use module with literal name

Topics: General
Oct 10, 2013 at 10:31 AM
underscore.string module is defined as follows:
declare module 'underscore.string' {
  function isBlank(str: string): boolean;
While underscore.d.ts declares:
declare module "underscore" {
    export = _;
How can I use it from my code ?
I've tried:
But tsc complains that:
error TS2095: Could not find symbol 'underscore'.
Oct 10, 2013 at 3:35 PM
When you declare a module name as a string that's declaring an AMD module that you would load with require. So this would work:
declare module 'underscore.string' {
  function isBlank(str: string): boolean;

import us = require('underscore.string');
That's assuming you have a module loader like requirejs available and the underscore.string module is located where it can find it.

If you're not using modules but objects loaded into the global namespace you can almost do this:
declare module underscore.string {
  function isBlank(str: string): boolean;


I say almost because string can't be a legal module name. If it was another word like "foo" then it would work.
Oct 10, 2013 at 3:55 PM
Yeah, I forgot to mention that I don't use module loader :(

I was hoping for some way of creating global alias:
import us = underscore.string; // or
import us = 'underscore.string';
but neither works.
Oct 10, 2013 at 9:04 PM
Edited Oct 10, 2013 at 9:09 PM
Nope if you don't want to use a module loader it's up to the script files you're loading to put everything in the global namespace.

I haven't tested this but glancing through the Underscore.string source it looks pretty smart. If it's not loaded as a CJS or AMD module it will do the right thing and install itself in the global _.string. If the module name wasn't string you could strip out the quotes to make it declare module underscore.string and that would just work. That doesn't work because string is reserved so we need to get a little fancier.

I turned the module into an interface and made it a member of _.
interface UnderscoreString {
     * Determine if a string is 'blank.'
     * @param str
    isBlank(str: string): boolean;

    // ... and so on


declare module _ {
    export var string: UnderscoreString;

I'd like to link the full Playground example to you but it's more characters than this forum will let me enter. I can't even find a url shortener that will allow it.

Edit: here's a pastebin.
Oct 10, 2013 at 11:05 PM
I took a less invasive approach and simply renamed module to _ since I'm mixing _.string into _.
Modules are the weakest part of typescript, causing only problems and confusion :(