Error: A variable is potentially 'undefined' (ts2532), even though I have just assigned a value to it

Encountering

Object is possibly 'undefined'. ts(2532)
errors in TypeScript for an optional parameter, despite being clearly defined...

interface Foo {
  keyValue?: Record<string, string>
}

const a: Foo = { keyValue: { key1: 'value' } }
a.keyValue.key2 = 'value2' // Object is possibly 'undefined'. ts(2532)

const b: Foo = {}
b.keyValue = { key1: 'value' }
b.keyValue.key2 = 'value2' // No error occurs

Curious why a.keyValue triggers the error while b.keyValue does not. The difference appears to be simply in verbosity of syntax.

Answer â„–1

When you use : Foo, TypeScript understands that the variable contains only the type Foo, where a property is optional.

const a: Foo = { keyValue: { key1: 'value' } }

To TypeScript, this declaration above is similar to:

declare const a: Foo;

By specifying : Foo, any properties not defined in Foo are considered optional.

However, if you do:

const b: Foo = {}
// At this point, b is exactly of type Foo
b.keyValue = { key1: 'value' }
// Now, b no longer matches the exact shape of Foo; it has the additional keyValue property

The property assignment occurs after the variable is declared as type Foo. Therefore, TypeScript can infer that the property exists based on the assignment, altering the shape of b from the original Foo with an optional property.

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

Discovering the method to access a local function within a static function in Javascript ES6 (ES2015) or Typescript

Is there a way to access the non-static "foo2" method from inside the static "bar" method? So far, I'm only able to access the "foo1" and "foo3" methods. Can anyone provide guidance on how to achieve this? let foo1 = () => { alert('foo1†...

Typescript does not support index signatures with bracket property accessor when importing using the `import * as`

Currently learning typescript and in the process of converting a large program from javascript. While fixing errors and adding types, I'm stuck on this one particular issue. Here's myModule.ts: export const foo = { ... } export const bar = { .. ...

Enforcing alias types in TypeScript arguments is necessary for maintaining consistency and clarity

I'm currently facing a challenge with type unions and aliases. I have an alias for values that can possibly be null or undefined, along with a function that handles these values. Everything is running smoothly and safely. However, there are instances ...

Transformation of Ionic 2 ScreenOrientation Plugin

Can someone assist me with this issue? A while back, my Ionic 2 app was functioning correctly using the ScreenOrientation Cordova plugin and the following code: window.addEventListener('orientationchange', ()=>{ console.info('DEVICE OR ...

After a loop, a TypeScript promise will be returned

I am facing a challenge in returning after all calls to an external service are completed. My current code processes through the for loop too quickly and returns prematurely. Using 'promise.all' is not an option here since I require values obtain ...

After integrating React Query into my project, all my content vanishes mysteriously

Currently, I am utilizing TypeScript and React in my project with the goal of fetching data from an API. To achieve this, I decided to incorporate React Query into the mix. import "./App.css"; import Nav from "./components/Navbar"; impo ...

Intro.js is not compatible with React and Remix.run

I am currently working on implementing onboarding modals for header links using intro.js within a React environment. Below is the code snippet: import { useState, type FC } from 'react' import type { Links } from '../types' import &apo ...

Angluar's pipe filter failing to provide unique outcomes

My application utilizes the same service data on both a Parent and Child page. While attempting to filter the data for unique values based on a specific column using ngx-filter-pipe module, I am encountering an issue where all values are still being retur ...

How can you update the property values of a CSS class that already exists in an Angular2+ controller?

In my styles.css file, I have a CSS class called '.users' with a property of color. Now, I am looking to dynamically change the color property value of the 'users' class based on certain conditions in my controller. For instance, I want ...

Utilizing Angular 2's pipe functionality with dynamic parameters

Currently I am diving into Angular2/Ionic2 and trying to grasp the concept of Pipes. Everything was going smoothly until I faced a roadblock in the form of a specific problem related to temperatures. Let me illustrate my issue with an example involving te ...

Potentially null object is present in a callback

The code I have is as follows: let ctx = ref.current.getContext("2d"); if(ctx){ ctx.lineWidth=1; // this line executes without errors ctx.strokeStyle=props.barStroke??"darkgray";// this line execut ...

In React Native, you can pass native component properties as props, while also defining custom ones using a TypeScript interface

I am working on a component called AppText where I need to utilize a Props interface and also be able to accept additional props that can be spread using the spread operator. However, I encountered this error: Type '{ children: string; accessible: tru ...

What is the proper way to compare enum values using the greater than operator?

Here is an example enum: enum Status { inactive = -1, active = 0, pending = 1, processing = 2, completed = 3, } I am trying to compare values using the greater than operator in a condition. However, the current comparison always results in false ...

How can I use the target type (and maybe even the property type) as a type parameter within a decorator?

In the process of incorporating a deep-watch property decorator in Angular, the following usage has been implemented: @Component({ /* ... */ }) export class AppComp { @Watch( 'a.b.c', function (last, current, firstChange) { // ca ...

Using Angular template to embed Animate CC Canvas Export

Looking to incorporate a small animation created in animate cc into an angular template on a canvas as shown below: <div id="animation_container" style="background-color:rgba(255, 255, 255, 1.00); width:1014px; height:650px"> <canvas id="canv ...

The functionality of Angular 4's ngStyle sum operates as a string instead of a number

<div class="scroll-element-content" [ngStyle]="{'width.px': (this.width + this.trackWidth)}"> With this.width set to 400 and this.trackWidth set to 8: The combined width of .scroll-element-content will be 4008 (since the sum is treated as ...

Enabling Event bus suggestions for Typescript: A step-by-step guide

Hello, I've encountered an issue while attempting to add types for the TinyEmitter library. Specifically, I need to define two methods. First: addEventListener(e: string, (...args: any[]) => void): void; Second: emit(e: string, ...args: any[]): vo ...

Determine the type of the final function within a variable number of nested closures

Imagine you have a function like this: const f = a => b => ... x => { return somevalue } Is there a way to determine the type of just the final function typeof x => { return somevalue } even if we don't know how many closures come before ...

Need assistance with the Angular polyfill.ts file? Wondering where to place the polyfill code and how to manage it effectively?

Currently encountering an error in my Angular project that requires some 'polyfilling'. Due to the restriction on editing webpack.config.js directly, it seems necessary to work with the polyfill.ts file instead. The issue lies in the fact that An ...

I'm having trouble setting a value for an object with a generic type

I am attempting to set a value for the property of an object with generic typing passed into a function. The structure of the object is not known beforehand, and the function receives the property name dynamically as a string argument. TypeScript is genera ...