What causes an Object to potentially be null even after Array.isArray(obj) check has been performed?

The provided code demonstrates TypeScript focusing on the line result[key].push(submenuKey); where it acknowledges that result might be null, but a check for Array.isArray() is included.

Code snippet:

interface resultI {
    [key: string]: string | null | any[];
}
const result: resultI = {
    fookey: ['foo', 'bar']
};

const key = 'fookey';
const submenuKey = 'submenuKey';

if (Array.isArray(result[key])) {
    result[key].push(submenuKey);
}

How does this work exactly?

Explore in playground

Answer №1

The reason behind the need for Array.isArray() is to protect the outcome of the result[key] expression. The second instance of result[key] represents a distinct expression that lacks protection (TypeScript cannot determine if it's guarded). To address this issue, you can store the value of result[key] in a variable and then safeguard the variable, as shown below:

...
const arr = result[key];
if (Array.isArray(arr)) {
    arr.push(submenuKey);
}

This situation arises because the key is a variable. In the case of a fixed key, the guard functions effectively, illustrated by the following example:

if (Array.isArray(result['fookey'])) {
    result['fookey'].push(submenuKey); // no errors
}

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

The data type 'string | null | undefined' cannot be assigned to the data type 'string | undefined'

In my Angular application using Typescript, I have the following setup: userId?: number; token?: string; constructor(private route: ActivatedRoute) { this.route.queryParamMap.subscribe( (value: ParamMap) => { this.userId = val ...

Utilizing Generic Types for Object Parameters

Why am I encountering an error when trying to use a function of type A for a B type one? How can I define a function type with unknown properties? When I attempt to define props in type B as props: Record<string, unknown>, it results in a similar err ...

Looking to modify the height and width of an image when it is hovered over using inline CSS

My current project involves working with a dynamic template where the HTML code is generated from the back-end using TypeScript. I am trying to implement inline CSS on hover, but despite having written the necessary code, it does not seem to work as intend ...

TypeScript interfaces do not strictly enforce properties when an object is assigned

Can someone help me understand TypeScript's rules for interfaces better? I am confused about why the following block of code throws an error due to the id property missing from the interface: interface Person { name: string; } let person: Person = ...

Having trouble getting the express router to function properly in your Node.js TypeScript project?

One of the components in this application is registerClass, where all routes are added. The source code is in the dist directory since this node app is using TypeScript. However, when calling the http://localhost:9001/user endpoint, it seems that it is not ...

Implementing various custom validation techniques in Angular 2

I am encountering an issue with adding multiple custom validations to a form. Currently, I am only able to add a single custom validation to my form. How can I include multiple validations? For example: this.user = this.fb.group({ name: ['', ...

When attempting to inject a provider from the same module, the dependencies cannot be resolved

Bug Report Current Issue Encountering an error when trying to instantiate the PaymentProcessorModule: Error: Nest cannot resolve dependencies of the PaymentProcessor (?, PaymentsService, ProcessingService). Please ensure that the TransactionsService argum ...

Ways to capture targeted requests

Utilizing NestJS and Angular 2, I have noticed that both frameworks have a similar approach when it comes to working with Interceptors. I am currently looking for the best practice to identify specific requests in order to perform additional tasks. When d ...

`mat chip component in Angular Material is malfunctioning`

Whenever I input a string, it does not display properly within the designated textbox. HTML <mat-form-field class="favorite-fruits"> <mat-label>Favorite Fruits</mat-label> <mat-chip-list #chipList aria- ...

Update: Increase the Date by one Month while formatting in the Moment

Months in MomentJs are indexed from 0 to 11. January is represented by 0 and December by 11. How can I elegantly format the date ensuring the correct month value is displayed? For instance: // if the date is 10.January.2020 moment(date).format('DDmm ...

What is the best way to send multiple parameters to @Directives or @Components in Angular using TypeScript?

I am facing some confusion after creating @Directive as SelectableDirective. Specifically, I am unclear on how to pass multiple values to the custom directive. Despite my extensive search efforts, I have been unable to find a suitable solution using Angula ...

Ways to convert all keys to uppercase in an array of objects?

Is there a way to capitalize the first letter of every key in an array of objects? I attempted to achieve this with the code below, but it's not working as expected. Any suggestions or corrections are appreciated. #current code function capitalizeO ...

Extending a Svelte component with a P5JS class: A step-by-step guide

As a newcomer to SO, I haven't asked many questions before, so please bear with me if I don't entirely follow the guidelines. I'll do my best to explain the issue at hand. In my project, I am utilizing Sveltekit (create-svelte) and P5JS (p5 ...

What could be causing the issue with my React Native app's release version not opening on a physical Android device?

I encountered an issue while trying to install the Release version of my application. In order to test both the debug and release versions on my physical and virtual devices, I utilized the following commands: ./gradlew assembleDebug, ./gradlew assembleRel ...

Issue encountered in Cypress while attempting to locate an identifier beginning with a numeric value

My struggle is with finding an element by id using Cypress. The Cypress selector playground provided the following code: get("#\33 -2") Unfortunately, when I execute this code in Cypress, it results in an error: Syntax error, unrecognized expressio ...

Can you explain the functionality of templates in the Primeng grid for Angular 6?

In my project, I am incorporating the use of primeng TurboTable which utilizes a pTemplate directive for templates. I am attempting to replicate this approach in order to create a reusable (DUMB) component. Despite my efforts to find a solution, I have not ...

Tips for handling TypeScript error TS2339 - Property does not found on type

Incorporating Angular 8 (initiated a project in Visual Studio 2019) and currently working with a fabric.init.ts file containing the following content: import 'fabric'; import * as fabric from 'fabric/fabric-impl'; // (TS) Property &ap ...

Combining the output of two Observables through the CombineLatest method to generate a

I possess two separate collections of information: Data Model: taxControlReference [ { "providerId": "HE", "taxTables": { "STAT": [ 1 ] } }, ...

Create TypeScript declaration files dynamically within the application's memory

Is there a way to programmatically generate declaration files using TypeScript? I know we can use tsc --declaration --emitDeclarationOnly --outFile index.d.ts, but I'm not sure how to do it in code. For example: import ts from 'typescript' c ...

The disappearing act of embedded Twitter timelines in Ionic 2

My code displays the timeline initially, but it disappears when I navigate away from the view. Can anyone help me troubleshoot this issue? Upon first visit to the view, the timeline is visible, but upon returning, it disappears. Below is the code snippet ...