我正在將 Nodejs 專案遷移到 TypeScript。從 開始index.js,將其index.ts更改為并為 ts 進行了必要的更改。但現在我遇到了錯誤
src/index.ts:34:90 - error TS2300: Duplicate identifier 'string'.
34 socket.on('login', async function ({ user_id:string}) {...}
我已經在混淆“重復識別符號”打字稿錯誤訊息中嘗試了大部分答案,但它們都沒有為我作業,其中包括:
npm install @types/node --save-dev并添加"typeRoots": ["node_modules/@types"]- 重新安裝
node_modules檔案夾 - 惹
compilerOptions
這是我的 tsconfig.json
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
// "typeRoots": ["node_modules/@types"], /* turn it on/off makes no difference */
"allowJs": true,
"sourceMap": true,
"outDir": "./build",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true
// "skipDefaultLibCheck": true, /* turn it on/off makes no difference */
"skipLibCheck": true
},
"files": ["src/index.ts"], /*I only want to tsc this file*/
"exclude": ["node_modules"]
}
我沒有安裝,@types/express但根據https://github.com/Microsoft/TypeScript/issues/247,“如果模塊沒有可用的型別資料(通過.d.ts檔案),ES6 模塊語法,必須使用 CommonJS選擇”。它似乎有效,所以我在我的代碼中混合require使用import。
這可能是原因嗎?
import { Server, Socket } from "socket.io";
var express = require('express')
var app = express()
var cors = require('cors')
var http = require('http').Server(app)
uj5u.com熱心網友回復:
您不能像那樣在函式引數解構中添加型別注釋。將您的代碼更改為:
socket.on('login', async function ({ user_id }: { user_id:string }) {...}
在回呼的簽名中,我們有常規的解構部分,{ user_id }但該函式的引數仍然是一個具有user_id屬性的物件,需要按原樣輸入。我將在下面使用提取的型別和未解構的引數重新撰寫它,以可能有助于給出想法:
type User = {
user_id: string
}
socket.on('login', async function (user: User) {
const user_id = user.user_id;
// do something
})
這相當于上面的行內版本,并且沒有語法快捷方式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/366078.html
