Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create definition file for local JavaScript module?

Let's say I have a a.js file that contains:

export function a() {}

and I want it to import it from the file b.ts (in the same directory) like that:

import { a } from './a.js'

How can I tell TypeScript what the file a.js contains so that compilation of this import succeeds?

like image 386
Kamil Szot Avatar asked Sep 15 '16 14:09

Kamil Szot


People also ask

Where do I put declaration file?

DefinitelyTyped / @types This will add a type declaration file for the loadash library under node_modules/@types/loadash folder. All the type declarations that is added via DefinitelyTyped / @types will be saved under node_modules/@types/<package-name> folder.

How do I include an external js file in another JavaScript file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file. This script tag should be included between the <head> tags in your HTML document.

What Is A TypeScript definition file?

TypeScript includes declaration files for all of the standardized built-in APIs available in JavaScript runtimes. This includes things like methods and properties of built-in types like string or function , top-level names like Math and Object , and their associated types.


2 Answers

What is needed for this to work is typescript definition file named same as JavaScript file (a.d.ts in this case) that contains:

export function a();

It can also specify parameter types, additional exported functions and classes and must use export keyword to indicate what the JavaScript file actually exposes.

One other change is that this JavaScript module needs to be then imported in b.ts as:

import { a } from './a' // without .js

so it takes typescript definition file into account. It will still use implementation from a.js file. It works with webpack too.


If you don't want to describe what's inside a.js and have TypeScript just accept it you can create a.d.ts file like that:

declare var whateva:any;
export = whateva;

Then you can import it like this:

import * as ajs from './a'

and then refer to any function exposed by a.js in your TypeScript files like that:

ajs.a();
like image 92
Kamil Szot Avatar answered Oct 20 '22 02:10

Kamil Szot


You can just simply use a statement:

declare var a:any;

(after the import) in this same file you are using the a (i this case in b.ts). Thanks to this the TS compiler will not complain. Also your IDE will not shown the errors.

like image 39
Baumi Avatar answered Oct 20 '22 03:10

Baumi