【问题标题】:Defining typings for npm react module for typescript为 typescript 的 npm react 模块定义类型
【发布时间】:2017-02-17 20:23:13
【问题描述】:

我正在尝试为反应模块react-input-autosize 定义类型,以用于打字稿项目。该模块没有现成的类型。

我将目录react-input-autosize 添加到typings/modules。 然后我在新目录中添加了一个文件index.d.ts。 我用我对导入模块结构的理解填充了新文件(打字稿编译器接受):

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

declare module 'react-input-autosize' {
  import * as React from "react"
  import * as ReactDOM from "react-dom"

  export interface AutosizeInputProps extends React.Props<any>{
      className?: string,     
      defaultValue?: any,     
      inputClassName?: string,
      inputStyle?: any, 
      minWidth?: number,
      onKeyDown?: (x:any) => void,
      onChange?: (x:any) => void,
      placeholder?: string,
      placeholderIsMinWidth?: boolean,
      style?: any,  
      value?: string,
      readOnly?: boolean,
      autoFocus?: boolean,
      type?: string
    }

  export class AutosizeInput extends React.Component<AutosizeInputProps, any> {
      constructor(props? : AutosizeInputProps, context? : any);

      greeting: string;
      showGreeting(): void;
  }

  export default AutosizeInput;
}

此时在项目中导入模块开始成功,因为我不再收到“找不到模块”错误:

import AutosizeInput from 'react-input-autosize';

不幸的是,实例化 AutosizeInput 类现在在运行时不起作用,因为 AutosizeInput 导致未定义。

在同一项目中的非打字稿文件中,import AutosizeInput from 'react-input-autosize'; 仍然有效,因此模块在未键入时从 npm 正确导入。

【问题讨论】:

    标签: reactjs typescript typescript-typings


    【解决方案1】:

    default导入:

    import AutosizeInput from 'react-input-autosize';
    

    将尝试导入default 导出。但是模块react-input-autosize 没有默认导出。你可以试试:

    import * as AutosizeInput from 'react-input-autosize';
    

    并从导出中删除 default

    export = AutosizeInput;
    

    希望对你有帮助。

    【讨论】:

    • 根据你的建议我得到error TS2497: Module ''react-input-autosize'' resolves to a non-module entity and cannot be imported using this construct.
    • 如果我将 AutosizeInput 类标记为 export default,那么编译器不会抱怨,但我无法在 react 中实例化该类,因为该符号显然为空。这意味着无论出于何种原因,我都可以让打字工作,但是导入不会在运行时加载类......
    猜你喜欢
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    • 2016-07-29
    • 2017-07-30
    • 2016-08-30
    • 2020-05-30
    • 2018-08-24
    • 2016-10-05
    相关资源
    最近更新 更多