Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

typescript

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; 
}
like image 476
Richard Avatar asked Jun 07 '16 12:06

Richard


People also ask

How do I import files into TypeScript?

To import a class from another file in TypeScript: Export the class from file A , e.g. export class Employee {} . Import the class in file B as import { Employee } from './another-file' . Use the class in file B .

How do I import all modules into a directory in TypeScript?

To import all modules from a directory in TypeScript, we can create a module that reexports all modules that were imported. export { default as A } from "./a"; export { default as B } from "./b"; to import the default exports from modules a and b .

Can I import JavaScript in TypeScript?

The allowJs setting allows JavaScript files to be imported inside your TypeScript files. The setting basically allows JavaScript and TypeScript files to live in the same project.


1 Answers

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');
like image 154
Blackus Avatar answered Sep 20 '22 16:09

Blackus