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" }]
}
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
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}`);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With