Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import JS in TS with noImplicityAny and without allowJs

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?

like image 655
crenshaw-dev Avatar asked Apr 22 '19 13:04

crenshaw-dev


People also ask

Can you use JavaScript in TypeScript file?

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.

How do I enable imports in TypeScript?

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.

How do you write JavaScript in Teamspeak?

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.


1 Answers

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.

like image 59
crenshaw-dev Avatar answered Oct 01 '22 02:10

crenshaw-dev