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.
So as explained by this post https://stackoverflow.com/a/40295288/10315665 the export default option only creates a default key inside of the exports object. That's why you can still have normal exports besides it.
Many people consider module.exports = ... to be equivalent to export default ... and exports.foo ... to be equivalent to export const foo = .... That's not quite true though, or at least not how Babel does it.
So your definition file is wrong. It should be:
declare type predicate = (v: unknown) => boolean;
export declare const names: {
[key: string]: string;
};
export declare const state: {
[key: string]: predicate;
};
export declare function talk(speech: string): void;
And if you respect that, you can actually utilize typescript and it's awesome type checking by simply writing typescript in the first place!:
export const names = {
firstname: "Alex",
middlename: "Blex",
lastname: "Clex",
};
export const state = {
isAlive() {
return true;
},
isWalking() {
return false;
},
};
export function talk(speech: string) {
console.log(speech);
}
Just remember to enable "declaration": true in the tsconfig to also generate declaration files ๐.