I have a problem where the Typescript compiler compiles my code successfully, yet the runtime gives me undefined type errors.
In my app I created a types.ts
file with some things shared between multiple other ts files. It contains a string enum like:
enum MyEnum {
One = "one";
Two = "two";
}
When I define it like this. The compiler lets me use it in other ts files, and appears to be happy. However, at runtime I get the error "MyEnum is not defined".
I know of two ways to solve this:
- Define the enum in the file where it is used. But I don't think this will solve anything for other files that want to use it.
- Use "export" in the types.ts file, and import every type explicitly everywhere it is used.
I am quite new to Typescript, and I feel I might be misunderstanding something fundamental.
First, I don't get why the Typescript compiler happily compiles my code if there's going to be a runtime error. I would understand it if I had used the declare
keyword, telling the compiler that something should be available at runtime, but in this case I don't see why it should assume that the enum comes from anywhere else then the types.ts file.
Second, I would like to define types somewhere globally in my app and have them be available everywhere without having to import them every time I used them. How do I accomplish this? Or is this maybe considered bad practice?
I am using Typescript 2.6 and my config looks like this:
{
"compilerOptions": {
/* Basic Options */
"target": "es6",
"module": "commonjs",
"lib": ["es6", "es7", "esnext"],
"sourceMap": true /* Generates corresponding '.map' file. */,
"outDir": "build" /* Redirect output structure to the directory. */,
"removeComments": true /* Do not emit comments to output. */,
/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
/* Additional Checks */
"noUnusedLocals": true /* Report errors on unused locals. */,
"noUnusedParameters": true /* Report errors on unused parameters. */,
"noImplicitReturns": true /* Report error when not all code paths in function return a value. */,
"noFallthroughCasesInSwitch": true /* Report errors for fallthrough cases in switch statement. */,
"plugins": [{ "name": "tslint-language-service" }],
"skipLibCheck": true // because firebase-sdk has wrong type files now (Nov 18)
},
"include": ["src/**/*"],
"exclude": ["build"]
}