亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

在 Create React App 中為節點模塊添加自定義 Typescript 類型聲明

在 Create React App 中為節點模塊添加自定義 Typescript 類型聲明

大話西游666 2021-09-30 17:55:39
我正在努力react-load-script在 Create React App 應用程序中添加類型聲明。在src文件夾中,我創建了一個react-load-script.d.ts文件并添加了以下內容:// Type definitions for React Load Scriptdeclare module 'react-load-script' {  import * as React from 'react'  interface Script {    url: string  }}有了上面的我得到錯誤:JSX 元素類型“腳本”沒有任何構造或調用簽名。我哪里錯了?這是模塊:https : //github.com/blueberryapps/react-load-script這是我目前在應用程序中的使用情況:<Script url="https://maps.googleapis.com/maps/api/js?                               key=your_api_key&libraries=places"              />我還需要為 onLoad 添加類型:<Script url="https://maps.googleapis.com/maps/api/js?                               key=your_api_key&libraries=places"                onLoad={this.handleScriptLoad}            />非常感謝。從評論更新我將聲明文件移動并重命名為 /@types/react-load-script/index.d.ts在tsconfig.json我添加以下內容compilerOptions:"typeRoots": ["./node_modules/@types", "./@types"]這是index.d.ts全部內容:// Type definitions for React Load Scriptimport React from 'react'export interface ScriptProps {  url: string  onLoad: () => void  // etc...}export default class Script extends React.Component<ScriptProps> {}有了這個,我仍然收到錯誤:找不到模塊“react-load-script”的聲明文件。'/Users/sb/git/fl-app/node_modules/react-load-script/lib/index.js' 隱式具有 'any' 類型。
查看完整描述

2 回答

?
手掌心

TA貢獻1942條經驗 獲得超3個贊

這是因為Script是組件,但您的界面定義了它的props.


按照 lib源代碼,您可能必須執行以下操作:


export interface ScriptProps {

  url: string;

  onLoad: () => void;

  // etc...

}


export default class Script extends React.Component<ScriptProps> {}

評論后編輯


您的類型涉及第三方模塊。你必須向 Typescript 提出建議。為此,您將在模塊聲明中封裝您的類型,如下所示:


// index.d.ts

declare module 'react-load-script' {

  // imports here...


  export interface ScriptProps {

    url: string;

    onLoad: () => void;

    // etc...

  }


  export default class Script extends React.Component<ScriptProps> {}

}


查看完整回答
反對 回復 2021-09-30
?
慕姐8265434

TA貢獻1813條經驗 獲得超2個贊

注意:在項目的根目錄中創建一個名為“custom-types”的文件夾,并在其中創建文件“index.d.ts”


索引.d.ts


declare module 'your-module-that-has-no-types';

配置文件


{

  "compilerOptions": {

    // ...other props,

    "typeRoots": ["./custom-types", "node_modules/@types"]

  },

  "include": [

    "src"

, "custom-types/index.d.ts"  ],

}


查看完整回答
反對 回復 2021-09-30
  • 2 回答
  • 0 關注
  • 285 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號