Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using React component library without @types

I'm developing React with TypeScript

What I want to do is to use React component library without @types definition.

I'd like to use this library
https://github.com/react-component/calendar

In my React code, I wrote as below

import * as React from "react";
import * as ReactDOM from "react-dom";
import Calendar from 'rc-calendar';

ReactDOM.render(<Calendar />, document.getElementById('content'));

but I get error:

ERROR in ./index.tsx
(4,22): error TS2307: Cannot find module 'rc-calendar'.

I'm guessing this is because there is no type definition but the library above seems not have type definition file for typescript.
How could I use such library with TypeScript?

like image 917
user2875308 Avatar asked Oct 24 '16 02:10

user2875308


People also ask

Can you React component without rendering?

Nope, render() method can't return an empty array or anything other than other React component.

Can you use React without classes?

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

Do I need to import React in every component?

1 Answer. Show activity on this post. You no longer need to import React from "react" . Starting from the release 17 of React, JSX is automatically transformed without using React.

Can we create React element without Babel?

We can create a React application without using these packages. It's true. For creating React applications, the least requirements are React and the ReactDOM package. React package helps us in creating a component.


1 Answers

In TypeScript 2.1, unless you're using --noImplicitAny, you will be able to just use this library without declaration files (provided that it's installed).

But since TS 2.1 isn't out yet, what you can do is create a file called externals.d.ts with the following content:

declare module "rc-calendar";

That basically tells TypeScript "hey, this thing exists, stop bugging me, and I want to use it however I want."

You can also give it a slightly better shape.

declare module "rc-calendar" {
    declare var calendar: any;
    export default calendar;
}

Now this thing can only be imported as a default import.

You can continue fleshing this thing out until it is sufficiently detailed.

like image 171
Daniel Rosenwasser Avatar answered Oct 27 '22 11:10

Daniel Rosenwasser