How to import JS in TS with noImplicityAny and without allowJs

强颜欢笑 提交于 2019-12-12 13:13:21

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/55795060/how-to-import-js-in-ts-with-noimplicityany-and-without-allowjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!