Typescript definition file (auto-generated) with a class that extends another class

420 Views Asked by At

I am having an issue with the auto generated d.ts file for a file that extends another class. We have a class structure like so: (TS Version 3.2.4)

export declare class MyBaseClass {
    id: string = '123';
    name: string = 'hello'
} 

we then have a class that extends this:

import { MyBaseClass  } from 'some-absolute-path/resources/my-base-class'

export declare class MyClass extends MyBaseClass {
    someProperty: string = 'test';
    someFunction(): void {
        console.log('hello');
    };
}

We then run tsc with the declarations flag on using this config file:

{
    "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "sourceMap": true,
        "sourceRoot": "src",
        "baseUrl": "src", 
        "moduleResolution": "node",
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "noEmitHelpers": false,
        "stripInternal": true,
        "declaration": true,
        "declarationMap": true,
        "outDir": "dist/commonjs",
        "lib": ["esnext", "dom"],
        "resolveJsonModule": true
    },
    "exclude": ["node_modules", ".vscode", "dist", "**/__tests__/*"]
}

The d.ts files seem to be generated fine:

my-base-class.d.ts

export declare class MyBaseClass {
    id: string;
    name: string;
}

my-class.d.ts

import { MyBaseClass  } from 'some-absolute-path/resources/my-base-class'

export declare class MyClass extends MyBaseClass  {
    someProperty: string;
    someFunction(): void;
}

We then pack this up as a npm package and install it in a separate project.

When we come to use MyClass in the consuming project we cannot access any of the base members of MyClass e.g.

const test = new MyClass();
test.id <----- Compile time Error in editor: TS2399 Property 'id' does not exist on type 'MyClass'

I'm obviously missing something here. What am I doing wrong here? Any help would be appreciated.

Thanks

EDIT: This seems to be related to absolute vs relative paths in the npm package. We have absolute paths in the library and the d.ts files also get generated with absolute paths. It seems as if when consuming these classes in the other app, it can't seem to find the imported classes by their path. I hacked the node_modules d.ts file to be relative import paths in the consuming project and it works ok. I can also change the paths in the npm package to be relative however I would like to avoid that.

0

There are 0 best solutions below