Typescript not getting any type information from a d.ts file for an existing js file

61 Views Asked by At

I suspsect that I'm doing something wrong here but if I have the existing file demo.js in a Node app which contains:

var Demo = function () {
    let self = this;
    self.sayGoodbye = (x) => `goodbye ${x}`;
};
module.exports = new Demo();

I would use this in a regular js file with

const demo = require('./demo');
demo.sayGoodbye('foo');

I've written a d.ts file called demo.d.ts that lives next to demo.js

export = Demo
declare class Demo {
    sayGoodbye(x: string) : string
}

In my new typescript file run.ts I've written the following:

const dem = require('./demo');
console.log(dem.sayGoodbye('foo'));

When I hover over the dem variable (in VSCode) the type is listed as any and I get no type information. Here is my tsconfig

{
    "compilerOptions": {
        "sourceMap": true,          // allow sourcemap support
        "strictNullChecks": true,   // enable strict null checks as a best practice
        "module": "commonjs",            // specify module code generation,
        "moduleResolution": "Node",
        "target": "es2015",            // specify ECMAScript target version
        "allowJs": true,             // allow a partial TypeScript and JavaScript codebase
        "experimentalDecorators": false,
        "types" : ["node"],
        "baseUrl":"."
    },
    "include": [
        "./**/*.ts",
    ],
    "exclude": [
        "node_modules"
    ]
}

If anyone could explain where I've gone wrong with d.ts or require statement I'd appreciate it.

Update:

I altered the d.ts file to this:

interface Demo {
    sayGoodbye(x: string) : string
}

declare var demo : Demo
export = demo

as I figured that the previous one wasn't actually representative of the file. If I understand it correctly the export of the inital one would have been a constructor function instead of an instance. If I now change the import statement in run.js to

import dem = require('./demo');
console.log(dem.sayGoodbye('foo'));

and I now get intellisense. Unfortunately the transpiled JS now has the following line:

Object.defineProperty(exports, "__esModule", { value: true });

It's not a deal breaker to have this present but I'd like to know how I can remove it but keep the require as the import for non-module based code.

0

There are 0 best solutions below