I'm using Webpack and @babel/typescript
to compile a mixed TypeScript and JavaScript project.
I'm using --noImplicitAny
to encourage taking advantage of typing.
I'm not using --allowJs
because my project is so big that it chokes the TypeScript compiler, and it destroys Visual Studio highlighting/Intellisense.
For un-typed npm modules, if I don't have time to add typings, I create a definition file to explicitly set its type to any
. For example
example.ts
import * as elemDataset from 'elem-dataset';
elem-dataset.ts
declare module 'elem-dataset';
That satisfies the compiler. But for internal modules I haven't yet converted to TS...
import * as example from './example2'; // Where example2 is example2.ts
I get this error:
Could not find a type declaration file for module './example2'. C:/blah/blah/blah/example2.js implicitly has 'any' type.
I've tried adding a type declaration, like in this answer.
example2.d.ts
declare var example2: any;
declare module "example2" {
export = example2;
}
But then I get this error:
File C:/blah/blah/blah/example2.d.ts is not a module.
I've also tried declare module '*';
per this answer, but I got the same error as above.
How can I explicitly set the import type of an internal JS file to any?
You can use thousands of existing JavaScript libraries in your TypeScript project. Type definition files allow you to enjoy the type-checking and autocomplete features in libraries that were written in JavaScript.
Use import myFunction from "./myModule" to bring it in. More commonly, TypeScript modules say export myFunction in which case myFunction will be one of the properties on the exported object. Use import { myFunction } from "./myModule" to bring it in.
TypeScript is a superset of JavaScript. This means that introducing TypeScript to your current JavaScript code is easy - just rename the . js file to . ts, and you're good to go.
Turns out this is sufficient for my needs:
// @ts-ignore
import * as x from './example2';
I didn't try it at first, because I thought that comment would disable type checking for the whole file.
But using @ts-ignore
just before the import allows me to enforce type checking for the rest of the project while ignoring a single JavaScript file until I have time to convert it.
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