Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type 'string | AddressInfo' has no property 'port' and no string index signature

Tags:

typescript

In { port } I got error: Type 'string | AddressInfo' has no property 'port' and no string index signature.

How to resolve it?

Code:

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

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

const { port } = app.address()

my 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" }]
}
like image 431
Yegor Zaremba Avatar asked Dec 12 '18 04:12

Yegor Zaremba


2 Answers

Found solution, it works for me:

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

const app = express()

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

const { port } = app.address() as AddressInfo
like image 94
Yegor Zaremba Avatar answered Nov 15 '22 02:11

Yegor Zaremba


In the example above it's clear that we should have a port, but if it weren't for some reason, you could use a typeof comparision as shown below:

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}`);
like image 30
Peter W Avatar answered Nov 15 '22 04:11

Peter W