user2875308 user2875308 - 2 months ago 46
TypeScript Question

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

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?


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.