带有声明文件的打字稿“找不到模块”

Ale*_* jg 1 typescript

我正在使用带有 react 的打字稿,并且需要为名为react-sticky. 我不想发布类型模块,我只想编写类型并将它们包含在我的代码库中,但我遇到了麻烦。这是设置

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>
}
Run Code Online (Sandbox Code Playgroud)

/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, {}>

}
Run Code Online (Sandbox Code Playgroud)

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" />
Run Code Online (Sandbox Code Playgroud)

我得到的错误如下

App.tsx(3,41): error TS2307: Cannot find module 'react-sticky'.
Run Code Online (Sandbox Code Playgroud)

现在,我是 Typescript 的新手,这里很可能有多个错误,有人知道我需要做什么吗?

Pel*_*obs 6

您快到了。由于这是您第一次声明模块“react-sticky”(<> 在其他地方增加声明),因此您必须将import 语句放在您的模块声明中。您的声明文件可能如下所示:

// 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>
}
Run Code Online (Sandbox Code Playgroud)

有趣的事实:

  • 您不需要在声明文件中添加导出
  • 您不需要在///任何地方添加引用,只要您没有将声明文件放在项目的根目录中。