How to import external library and cast it to <any> in Typescript?

情到浓时终转凉″ 提交于 2021-02-20 05:41:26

问题


TypeScript was giving me a compile error that I didn't know how to fix when trying to use a React component I defined:

import App = require('./components/views/app/app');

That error went away when I used the import module as <any>:

import App = require('./components/views/app/app');
const App2 = App as any;

Is there any way to do this in one line, like so?

import App = require('./components/views/app/app') as <any>;

It would be a great way to import JavaScript files too, without having to do this:

declare module 'react-router' {
    const x: any;
    export = x; 
}

回答1:


For the components you have defined, it depends on how you export them, but you can use import statement.

For example, the exported component

export class FooComponent extends React.Component<any, any> {
}

And the import

import {FooComponent} from './foo-component.ts';

For the question on the title "How to import external library and cast it to any", you can simply require on a variable.

const myLib: any = require('myLib');


来源:https://stackoverflow.com/questions/37679889/how-to-import-external-library-and-cast-it-to-any-in-typescript

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