3

I'm new to TypeScript and I want to know how to write declaration file for custom JavaScript function. I tried this, but it give me error "Could not find a declaration file for module './main'." and don't give any IntelliSense in index.ts file.

main.js

var maths={ sum:function (a,b){ console.log(a+b)}}

module.exports=maths;

index.ts

import * as mt from "./main"
mt.sum(2,5);

type.d.ts

 declare module 'main' {
export function sum(a:number,b:number):void }

`

1 Answer 1

1

This import

import * as mt from "./main"

is looking for either main.ts or main.d.ts in the same directory as index.ts.

So one thing you can try is to rename type.d.ts to main.d.ts and remove declare module 'main' from it, leave just export function sum at the top level. When imported that way, module name is taken from the file name. Also, you might have to remove reference to type.d.ts from your project (or tsconfig.json) if you have one.

ALternatively, you can try to change the import to

import * as mt from "main"

so that imported module name matches exactly the name given in declare module.

Sign up to request clarification or add additional context in comments.

2 Comments

Appreciate the answer and it works.One more thing need to ask should be both d.ts file and .js file in same folder ?
for import from "./main", main.js file should be in the same folder where compiled index.js is.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.