reactjstypescripttypescript-typingsreact-datetime

How to use react-datetime with react + typescript (inside tsx)


react-datetime has a typescript definition file included, but it does not work (for me). From what I can see, the ts definition file exports a different type (ReactDatetime) than what is in actual javascript file (Datetime).

I went ahead and changed react-datetime.d.ts typings file to export the (what I think) is correct type (available in gist):

interface Datetime extends React.ComponentClass<DatetimepickerProps> {}
export { Datetime }

And TypeScript complains that it can not find the Datetime:

(26,10): error TS2304: Cannot find name 'Datetime'.

I guess there's something pretty basic I must be missing in terms of typings and this component. Trying to make it work with the original typings file resulted in inability to import the module in the first place, even though the react-datetime.d.ts file was referenced using /// <reference path="../node_modules/react-datetime/react-datetime.d.ts" /> directive.

A minimalistic example of class trying to use <Datetime/>:

/// <reference path="../../node_modules/react-datetime/react-datetime.d.ts" />
import * as React from "react";
import { Datetime } from "react-datetime";


export interface DateTimeResolutionProps { timestamp: number, resolution: number }
export class DateTimeResolutionPicker extends React.Component<DateTimeResolutionProps, {}> {
    render() {
        // console.log(Datetime);
        return (<div>
        <Datetime/>
        </div>);
    }

}

Solution

  • You should import it just like you imported the React module:

    import * as Datetime from "react-datetime";
    

    Then it won't complain about not finding the Datetime.

    As for the names, you decide what the name will be, it can be ReactDatetime if you want:

    import * as ReactDatetime from "react-datetime";
    

    The same happens with the React module, if you look at the definition file it will show:

    declare namespace __React {
        ...
    }
    
    declare module "react" {
        export = __React;
    }