输入'string | AddressInfo'没有属性'port'并且没有字符串索引签名

时间:2018-12-12 04:48:12

标签: typescript

{ port }中出现错误:输入'string | AddressInfo”没有属性“ port”,也没有字符串索引签名。

如何解决?

代码:

import * as express from 'express'
const app = express()

app.listen({ port: process.env.PORT })

const { port } = app.address()

我的tsconfig.json

{
  "compilerOptions": {
    "target": "es6",
    "module": "commonjs",
    "lib": ["dom", "es6", "es2017", "esnext.asynciterable"],
    "sourceMap": true,
    "outDir": "./dist",
    "moduleResolution": "node",

    "composite": true,
    "removeComments": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "strictFunctionTypes": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    "allowSyntheticDefaultImports": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "baseUrl": ".."
  },
  "exclude": ["node_modules"],
  "include": ["./src/**/*.tsx", "./src/**/*.ts"],
  "references": [{ "path": "../common" }]
}

2 个答案:

答案 0 :(得分:1)

在上面的示例中,很明显我们应该有一个端口,但是如果由于某种原因而没有端口,则可以使用typeof比较,如下所示:

import * as express from 'express'
const app = express()

app.listen({ /* some args from config perhaps, and not necessarily "port" */})

const addr = server.address();
const binding = typeof addr === 'string'
    ? `pipe/socket ${addr}`
    : `port ${addr.port}`;
console.log(`? Server listening on ${binding}`);

答案 1 :(得分:0)

找到解决方案,它对我有用:

import * as express from 'express'
import { AddressInfo } from 'net'

const app = express()

app.listen({ port: process.env.PORT })

const { port } = app.address() as AddressInfo