LDJ
LDJ

Reputation: 7314

Typescript: using an enum declared in another file

Say I've got an enum declared in one file (test1.ts):

export enum Colors{
    red=1,
    blue=2,
    green=3
}

Then in another file (test2.ts) I'm declaring a class which has a method. One of the parameters to that method is a Color defined in the Colors enum:

'use strict';
declare var require: any;
declare var exports: any;

var Colors = require('Colors');

class DoSomethingWithColor{
    ColorFunction(aColour:Colors){
        //Funky color processing here..
    }
}

However, I'm getting an error:

Cannot fine name Colors

Even though its exported and required in the second file. Am I doing something wrong here or is this just not a 'typescripty' way of doing what I'm trying to do (and if so, what is the preferred way?)?

Thanks

Upvotes: 9

Views: 12237

Answers (1)

dracstaxi
dracstaxi

Reputation: 2687

As was mentioned by jonrsharpe in the comments you have to use one of the typescript supported import statements.

import * from './test1' as Colors

or

import {Colors} from './test1'

For more information on import statements and best practices regarding modules (now namespaces) in typescript, please check out their documentation: https://www.typescriptlang.org/docs/handbook/modules.html https://www.typescriptlang.org/docs/handbook/namespaces-and-modules.html

Generally if you are using export/import statements a module loader like CommonJS or WebPack will be required. These programs bundle your code and are responsible for ensuring that dependencies are available to the importer at runtime. Judging by the fact that the import statement worked out of the box, it is likely that you were already using a module loader.

Upvotes: 4

Related Questions