Utilizing the `in` operator for type narrowing is yielding unexpected results

Attempting to narrow down a type in TypeScript:

const result = await fetch('example.com')

if (typeof result === "object" && "errors" in result) {
  console.error(result.errors);
}

To clarify, the type of result before the if condition should be unknown.

However, I encounter error

TS2339: Property 'errors' does not exist on type 'object'.

It seems like TypeScript is ignoring the in keyword. I included typeof result === "object" to verify the use of in in this context.

Interestingly, my IDE does not flag any issues with this code:

if (typeof result === "object" && "errors" in result) {
  console.error(result["errors"]);
}

However, TypeScript does not seem to check this since there are no complaints with this code either:

if (typeof result === "object" && "errors" in result) {
  console.error(result["nothere"]);
}

Any insights on this matter?

Answer №1

Trying to insert a key into an existing type using the in operator is not possible.

You must explicitly inform the compiler that the key could potentially exist:

const result: Response & { errors?: unknown } = await fetch('example.com')

if (typeof result === "object" && "errors" in result) {
    console.error(result.errors);
}

Interactive Playground

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

Error TS2394: Function implementation does not match overload signature in Typescript

Take a look at this code that seems to be causing headaches for the TypeScript compiler: use(path: PathParams, ...handlers: RequestHandler[]): this use(path: PathParams, ...handlers: RequestHandlerParams[]): this use(...handlers: RequestHandler[]): this u ...

The functionality of the KendoReact Grid for filtering and sorting is not functioning correctly when data is grouped

Once I group the data, the filter and sort functions in the KendoReact Grid stop working. Interestingly, if I bypass the grouping step and show the data without grouping, the filter and sort functions function perfectly fine. My main objective is to figu ...

The error message states that the type '{}' does not contain the property 'API_BASE_URL'

Encountering this error message when trying to access my API_URL as defined in the enviroment.ts file within a service class. Error: src/app/product/product.service.ts:12:25 - error TS2339: Property 'API_BASE_URL' does not exist on type '{} ...

Issue TS2339: The object does not have a property named 'includes'

There seems to be an issue that I am encountering: error TS2339: Property 'includes' does not exist on type '{}'. This error occurs when attempting to verify if a username is available or not. Interestingly, the functionality works ...

The interface IJobDetails cannot be assigned to type null

https://i.sstatic.net/cVVSs.png In the code snippet below, I have created an interface called ClientState1. Now, I am attempting to define a constant named descriptionJobDetails with the type ClientState1, specifically for IJobDetails. However, I am encou ...

Interface in React Typescript does not include the specified property

Just starting out with React after some previous experience with Angular. I've been trying to create a component that accepts a data model or object as a parameter. Here's what I have: import react from 'react' interface SmbListItem{ ...

Unraveling the Perfect Jest Stack Trace

Currently, I am in the process of debugging some tests that were written with jest using typescript and it's causing quite a headache. Whenever a test or tested class runs Postgres SQL and encounters an error in the query, the stack trace provided is ...

What is the importance of adding the ".js" extension when importing a custom module in Typescript?

This is a basic test involving async/await, where I have created a module with a simple class to handle delays mymodule.ts: export class foo { public async delay(t: number) { console.log("returning promise"); ...

The ngfor loop seems to be caught in an endless cycle of continuously executing functions and

I am currently working on a sophisticated reporting solution. Essentially, I have created a table using an ngFor loop where I have implemented certain conditions that allow the user to view details of a clicked element by expanding and collapsing it. The ...

Incorporate a background image into mat-dialog

I've been struggling to set a background image on my mat-dialog, but for some reason it's not showing up at all. I attempted using a panelClass as well, but still no luck. .custom-panel .mat-dialog-container { background-image: url("../. ...

Stop receiving updates from an Observable generated by the of method

After I finish creating an observable, I make sure to unsubscribe from it immediately. const data$ = this.httpClient.get('https://jsonplaceholder.typicode.com/todos/1').subscribe(res => { console.log('live', res); data$.unsubscr ...

Where specifically in the code should I be looking for instances of undefined values?

One method in the codebase product$!: Observable<Product>; getProduct(): void { this.product$ = this.route.params .pipe( switchMap( params => { return this.productServ.getById(params['id']) })) } returns an ...

Angular2 Eclipse: Eclipse Oxygen's HTML editor detects TypeScript errors in real-time

After installing the Eclipse Oxygen plugin for Angular2, I created a project using the Angular CLI and opened it in Eclipse. However, when trying to convert the project to an Angular project, I couldn't find the option under configuration. Instead, th ...

Customizing Material UI Select for background and focus colors

I am looking to customize the appearance of the select component by changing the background color to "grey", as well as adjusting the label and border colors from blue to a different color when clicking on the select box. Can anyone assist me with this? B ...

Issues with Typescript and TypeORM

QueryFailedError: SQLITE_ERROR: near "Jan": syntax error. I am completely baffled by this error message. I have followed the same steps as before, but now it seems to be suggesting that things are moving too slowly or there is some other issue at play. ...

Is it recommended to employ cluster connection within my Redis client when utilizing Azure Redis Cluster?

It seems that the Azure documentation on clustering can be a bit confusing. According to the docs: Will my client application need any modifications to support clustering? Once clustering is activated, only database 0 will be accessible. If your client ...

What is the recommended way to use the async pipe to consume a single Observable property in a view from an Angular2

Suppose I have a component with the following property: import { Component, OnInit } from 'angular2/core'; import { CarService } from 'someservice'; @Component({ selector: 'car-detail', templateUrl: './app/cars/ ...

server running on node encountered an error due to a port that is already in use

The Server instance emitted an 'error' event at: at emitErrorNT (net.js:1340:8) at processTicksAndRejections (internal/process/task_queues.js:84:21) { code: 'EADDRINUSE', errno: 'EADDRINUSE', syscall: 'listen', addre ...

Challenges encountered when testing middleware in a TypeScript Node.js Express project

I have been exploring the repository at https://github.com/goldbergyoni/nodebestpractices to enhance my understanding of nodejs best practices. Below is a middleware I developed: import { NextFunction, Request, Response } from "express"; import ...

An effective method for excluding null values with an Angular pipe

I am currently working on an Angular pipe that filters results based on user input. The problem I'm encountering is that some of the results do not have a value, resulting in this error message: Cannot read property 'toLocaleLowerCase' o ...