Alex jg
Alex jg

Reputation: 1005

Typescript 'Cannot find module' with declaration file

I'm using typescript with react and need to provide typings for a third party library called react-sticky. I don't want to publish a typings module, I just want to write the typings and include them in my codebase, but I'm running into trouble. Here's the setup

App.tsx

/// <reference path="./typings/index.d.ts" />
/// <reference path="./typings/react-sticky.d.ts" />
import * as React from "react"
import { Sticky, StickyContainer } from "react-sticky"

const App: React.StatelessComponent<{}> = () => {
    return <StickyContainer>
        <Sticky>
        <h1>Hello World</h1>
        </Sticky>
    </StickyContainer>
}

/typings/react-sticky.d.ts

/// <reference path="./modules/react/index.d.ts" />
import * as React from "react"

declare module "react-sticky" {

    export var StickyContainer: React.Component<{}, {}>
    export interface StickyProps {
        stickyStyle?: any
        stickyClassName?: string
        topOffset?: number
        bottomOffset?: number
        className?: string
        style?: {}
        onStickyStateChange?: () => void
        isActive?: boolean
    }
    export var Sticky: React.Component<StickyProps, {}>

}

typings/index.d.ts

/// <reference path="modules/react-dom/index.d.ts" />
/// <reference path="modules/react/index.d.ts" />
/// <reference path="react-sticky.d.ts" />

The error I'm getting is the following

App.tsx(3,41): error TS2307: Cannot find module 'react-sticky'.

Now, I'm new to Typescript, there are quite possibly multiple errors here, anyone know what I need to do?

Upvotes: 1

Views: 5963

Answers (1)

Pelle Jacobs
Pelle Jacobs

Reputation: 2589

You're almost there. As this is the first time you declare the module 'react-sticky', (<> augmenting a declaration somewhere else), you'll have to put the import statement inside of your module declaration. Your declaration file could look something like this:

// custom_typings/react-sticky.d.ts
declare module "react-sticky" {
  import * as React from "react"
  var StickyContainer: React.ComponentClass<{}>
  interface StickyProps {
    stickyStyle?: any
    stickyClassName?: string
    topOffset?: number
    bottomOffset?: number
    className?: string
    style?: {}
    onStickyStateChange?: () => void
    isActive?: boolean
  }
  var Sticky: React.ComponentClass<StickyProps>
}

Fun facts:

  • you don't need to add exports in your declaration file
  • you don't need to add the /// reference anywhere, as long as you're not putting your declaration file in the root of your project.

Upvotes: 6

Related Questions