Before you consider my question as duplicate, I already tried everything answered in other questions and no success. Let me explain my problem:
I have an Angular 2 App and an Express API sharing a private package written in Typescript that contains classes for my domain. All of them are using Typescript 2.2.2.
In the priavte package there is a class that extends another class in another file and the project compiles. The problem happens when I try to use the package in my Angular app: everything breaks and the console shows TypeError: Object prototype may only be an Object or null: undefined.
That only happens if the child class is present in the package, otherwise everything works fine.
Ex:
// child/child.ts
import { Parent } from '../parent/parent';
export class Child extends Parent { }
// parent/parent.ts
export class Parent {
foo: string;
}
// bar/bar.ts
import { Child } from '../child/child';
export class Bar {
child: Child;
}
In the private package I'm using Gulp to compile Typescript to Javascript and generate the declarations file.
Here is the .tsconfig file:
{
"compilerOptions": {
"target": "es5",
"noImplicitAny": true,
"preserveConstEnums": true,
"sourceMap": true,
"experimentalDecorators": true,
"typeRoots": ["../node_modules/@types"],
"declaration": true,
"removeComments": false
},
"include": [
"**/**.ts"
],
"exclude": [
"node_modules"
]
}
Here is the .gulpfile.js:
var gulp = require('gulp');
var ts = require('gulp-typescript');
var merge = require('merge2');
var tsConfig = ts.createProject('tsconfig.json', { declaration: true });
gulp.task("release", [], () => {
var tsResult = gulp.src('src/**/**.ts')
.pipe(tsConfig());
return merge([
tsResult.dts.pipe(gulp.dest('release/definitions')),
tsResult.js.pipe(gulp.dest('release/js'))
]);
});
My files structure:
+ root
|
+--+ bar
| |
| +-- bar.ts
|
+--+ child
| |
| +-- child.ts
|
+--+ parent
|
+-- parent.ts
I've read that it could be a problem with sorting the classes names when compiling, because Parent has to be compiled before Child. The solution would be writing the directive /// <reference path="parent/parent"> in my child class, but when I try to compile it fails and says the reference directive doesn't exist. If I write references instead of reference it compiles, but the resulting js files are the same, except by that extra line, and don't work.
in your tsconfig file, you dont have a baseUrl so typescript cannot resolve this import in bar/bar.ts: import { Child } from 'child/child';
to resolve this you need to switch your import to the relative path to 'child' file.
IF your directory structure was
root
--bar
----bar.ts
--child
----child.ts
then your file becomes:
// bar/bar.ts
import { Child } from '../child/child'; // <---
export class Bar {
child: Child;
}