Today I was writing a type declaration file for a JavaScript file but despite my hours of trying I couldn't make it work inside a node application. Then I tried switching to es6 module syntax and surprisingly it worked.
Then I discovered that I can also make it work with commonjs module syntax if I add ".default"
before accessing any properties of that module. For example I've to use person.default.name
instead of person.name
to get the intellisence.
I wrote a small module to demonstrate the problem. I've created an object with identical typings of my actual module.
index.js
const names = {
firstname: "Alex",
middlename: "Blex",
lastname: "Clex",
};
const state = {
isAlive() {
return true;
},
isWalking() {
return false;
},
};
function talk(speech) {
console.log(speech);
}
const person = {
names,
state,
talk
};
module.exports = person;
index.d.ts
declare type predicate = (v: unknown) => boolean;
declare function talk(speech: string): void;
declare const person: {
names: {
[key: string]: string;
};
state: {
[key: string]: predicate;
};
talk: typeof talk;
};
export default person;
test1.js
const person = require("./index");
const isAlive = person.default.state.isAlive();
//---------------------^^^^^^^----------------
// The above line throws an error as expected.
// I've to use "person.default.whatever" to get intellisence
// In the editor it shows "typeof isAlive = boolean".
const isReallyAlive = person.state.isAlive();
// EditorError: Property 'state' does not exist on type
// 'typeof import(./index.js)'.
// In the editor it shows typeof "isReallyAlive = any"
// But infact isReallyAlive is boolean.
test2.js
Using es6 module syntax it works perfectly.
I'm fairly new to Typescript so kindly give me some hint where I'm making the mistake.
Thanks in advance, I highly appreciate your time on StackOverflow
<3.