The type 'string | AddressInfo' does not include a 'port' property and does not have a string index signature

When running in { port }, I encountered the following error: Type 'string | AddressInfo' has no property 'port' and no string index signature.

How can I resolve this issue?

Code:

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

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

const { port } = app.address()

Here is 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" }]
}

Answer №1

I have discovered a solution that works perfectly for me:

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

const server = express()

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

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

Answer №2

When looking at the scenario presented above, it becomes evident that having a port is essential. However, if for some reason a port is not available, one could resort to utilizing a typeof comparison technique as illustrated below:

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

app.listen({ /* various parameters extracted from configuration, potentially not limited to "port" */ })

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for including a dash or hyphen in an input field after two digits in Angular 4

Struggling to format the date of birth input with dashes manually when entered by the user. The desired output should resemble "08-18-2019," but I'm having difficulty achieving this. public dateOfBirth: { year: number; month: number; day: number }; ...

Experience Next.js 13 with Chakra UI where you can enjoy Dark Mode without the annoying White Screen Flash or FOUC (flash of unstyled content)

Upon refreshing the page in my Next.js 13 /app folder application using Chakra UI, I notice a few things: A momentary white flash appears before switching to the dark theme. The internationalization and font settings momentarily revert to default before l ...

Eliminate the need for require statements in TypeScript-generated JavaScript files

I am working on a website project and utilizing TypeScript for development. While using the tsc compiler, I noticed that all my JavaScript code compiles correctly. However, when I include an import statement in my TypeScript files, it gets compiled into J ...

Separating the time and date into distinct variables offers flexibility in how they

Struggling with formatting time in a web component using TypeScript and React. The code below is working: new Date(myDate) .toLocaleTimeString( 'en-US', { weekday: 'short', year: 'numeric', month: 'short', ...

Looping issue with ForEach in Typscript with Firebase Functions

While browsing through various questions on this topic, I've noticed that the specific answers provided don't quite fit my situation. My query involves converting a Google Firebase RTB datasnapshot into an array of custom objects, each representi ...

Struggling to integrate D3.js with React using the useRef hook. Any suggestions on the proper approach?

I'm currently working on creating a line chart using d3.js and integrating it into React as a functional component with hooks. My approach involved utilizing useRef to initialize the elements as null and then setting them in the JSX. However, I encou ...

Issue with esbuild not executing within docker compose configuration

Currently, I am new to using esbuild and struggling to set up a script that can watch and rebuild my files. Additionally, I need this functionality to work within a docker environment. Within my package.json file, the following scripts are defined: " ...

In Angular 2, how does the "this" keyword from the subscribe method reference the class?

I am using a subscription for Observable, and when it finishes I need it to call a function from this class. The issue is that the "this" keyword refers to the subscription and not to the class scope. Here is the code snippet: export class GoogleMapCompo ...

What steps should be taken to enable SCSS in Jest for unit testing in TypeScript Next.js?

I am facing an issue with the scss import in my project. I have attempted to solve it by using mockup and identity-obj-proxy, but neither of them seems to work. I suspect that there might be a problem with my regex expression. The specific error arises fr ...

Error encountered during Typescript compilation: The attribute 'raw' is not found within the context of the entity 'e' in express

In many instances, I have noticed that people use express.raw() or express.raw({type: 'application/json'}) as middleware in their requests... but is .raw() a legitimate method in Express? I am currently working with TypeScript and using Express ...

TypeScript allows for the declaration of a function that includes a mandatory property within the function signature

If I desire a tagged function with an interface such as: interface TaggedFun { (args): void; tag: boolean; } It appears that declaring a function to match this signature is not possible (since any function literal will lack the mandatory tag prop ...

Difficulty fetching data on the frontend with Typescript, React, Vite, and Express

I'm currently working on an app utilizing Express in the backend and React in the frontend with typescript. This is also my first time using Vite to build the frontend. While my APIs are functioning correctly, I am facing difficulties fetching data on ...

A function that logs a message to the console if an array contains identical values

Struggling to find equal values in my array, I've attempted several methods without success. One approach I tried involved sorting the array: var sorted_arr = this.variacaoForm.value.variacoes.sort(); // the comparing function here for (var i = 0; ...

Is there a solution available for the error message that reads: "TypeError: Cannot set value to a read-only property 'map' of object '#<QueryCursor>'"?

Everything was running smoothly in my local environment, but once I deployed it on a Digital Ocean Kubernetes server, an error popped up. Any assistance would be greatly appreciated. https://i.stack.imgur.com/VxIXr.png ...

Leveraging the power of literal types to choose a different type of argument

My API is quite generic and I'm looking for a typed TypeScript client solution. Currently, my code looks like this: export type EntityTypes = | 'account' | 'organization' | 'group' export function getListByVa ...

Tips for utilizing functions in an inline HTML translation pipe

My objective is to streamline the code by using the Angular translate pipe. Currently, I find myself using 8 curly brackets and repeating the word "translate" twice... there must be a more efficient approach. Here is my current code setup: <s ...

TS7016: No declaration file was found for the module named 'rxjs'

I recently updated my Angular App dependencies and successfully installed them. However, I am now facing an issue with 'rxjs'. The IDE returned the following error: TS7016: Could not find a declaration file for module 'rxjs'.'C:/ ...

SystemJS TypeScript Project

I am embarking on a journey to initiate a new TypeScript project. My aim is to keep it simple and lightweight without unnecessary complexities, while ensuring the following: - Utilize npm - Implement TypeScript - Include import statements like: import ...

TypeScript's conditional property failing to recognize incorrect functional argument

The concept of a conditional type should encompass smart properties, and I sought assistance from @jcalz in the previous iteration of this query. Even though that issue was resolved, I am still unable to achieve the level of typing strictness I desire. The ...

While making changes, I was anticipating a "for-of" loop to be used instead of a "for" loop

There seems to be an issue with TSlint and its disapproval of using the traditional for(i=0; ...) loop. Consider this straightforward code snippet: this.filters['1','2','3'....]; for (let i = 0; i < this.filters.length; i+ ...