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?
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.
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.
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.
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();
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With