#請益 Node.js 的 @types/express 與 express 的差異?

我想使用 Typescript 開發網站,使用 @types/express 但為什麼還要安裝 express ? 那我是不是每一個 @types/* 都要安裝對應的 npm package ??? 目前 package.json 非常單純: { "devDependencies": { "@types/express": "^4.17.13", "@types/node": "^18.7.13", "nodemon": "^2.0.19", "typescript": "^4.8.2" }, "dependencies": { "dotenv": "^16.0.1", "express": "^4.18.1", "pg": "^8.8.0", "reflect-metadata": "^0.1.13", "typeorm": "^0.3.8" } } 就是這個 @types/express 和 express 造成我的疑問 我的認知是 Typescript 可依tsconfig.json編譯成 JavaScript 給 Nodejs 運行 也就是說我把 @types/express 跑 tsc app.ts 編譯成 app.js 給 Nodejs 理論上應該可以成功 但編譯後 Nodejs 會認不出 express 是甚麼,還要另外裝 express ?? (what?) 另一個問題 那我不編譯 TS 可以直接運行 @types/express server 嘛?直接捨棄編譯那塊
``` Romain Bruckert(answered): I'v run into this issue myself and found out you also have to have the actual nodeJS module installed as well as its typing. So when you have correclty configured typescript and your project, you need ot install both the nodeJS dependency as well as the @types dependecy. ```
sticker
愛心
2
4
全部留言
express 是套件本體,不論 js/ts 都能跑 (前提是 ts disable 相關檢查的話) @types/express 是定義型別給 ts 檢查,如這個變數應該是 array,不應該是其他類別 p.s. 這也是為什麼 @types/express 是裝在 devDependencies 開發環境而在 dependencies 生產環境不需要
B1(已編輯)
你對 @types/* 有誤解,他不是 library 的 TypeScript 版本,只是 library 的型別定義檔案而已。就算你安裝了 @types/express & express 後,實際在執行的是 express,@types/express 只是輔助而已 在 TypeScript 發明前,已經有很多 JavaScript 的 library 存在了,因此這些 library 當初在開發時沒有型別的概念,跟 TypeScript 一起用會有問題。為了解決這個問題,於是有人幫這些沒有型別概念的 library 補上型別定義檔,這就是 @type/* See also:
B2(已編輯)