How come TS doesn't throw an error when obj['NonExistentKey'] is accessed?

Review the code snippet below to understand how errors are handled:

const foo = { someKey: 'foo' };
foo['NonExistentKey'].bar.baz // no errors
foo.NonExistentKey.bar.baz    // NonExistentKey doesn't exist

Click here for TypeScript playground link

Can this be caught in any way?

Answer №1

When transitioning from JavaScript to TypeScript, it was decided that dynamic object access using [] should not result in an error and simply return any value.

However, this introduces a significant weakness in the type system, which can be addressed by using a compiler flag called noImplicitAny. Enabling this flag will cause errors to be raised as expected (but keep in mind that the compiler may also flag instances where it assumes any as an error).

If you explore the TypeScript playground and enable this option under settings, you will observe the anticipated error message.

Answer №2

If you want to easily catch errors of this type, consider turning on TypeScript's strict mode or enabling the noImplicitAny flag in your tsconfig.json configuration file.

Once one of these options is activated, you will receive an error message similar to the following:

wat.ts:2:1 - error TS7017: Element implicitly has an 'any' type because type '{ someKey: string; }' has no index signature.
foo['NonExistentKey'].bar.baz

In the absence of these flags, the variable foo is automatically typed as

const foo: { [index: string]: any, someKey: string }
. This decision is based on the fact that JavaScript developers often access properties of objects using arbitrary indexes without defining explicit types, which may not be a safe practice in terms of type-checking.

Personally, I find the behavior allowed by non-strict mode to be confusing and potentially error-prone. Therefore, I recommend setting strict: true in your tsconfig.json file for better code quality and safety.

You can refer to the full documentation on TypeScript compiler options here.

For more information about tsconfig.json configurations, visit this link.

Additional details on index signatures in TypeScript can be found here.

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

Guide on assigning JSON response values to TypeScript variables in Angular 4

I'm just starting with Angular 4 and I'm attempting to retrieve a JSON value using http.post. The response I'm receiving is: {"status":"SUCCESS"} component onSubmit(value: any) { console.log("POST"); let url = `${this.posts_Url}`; t ...

Visibility of an Angular 2 directive

It's frustrating that I can't change the visibility of a reusable directive in Angular2. 1) Let's say I have a login page. I want to control the visibility of my navbar based on whether I am on the login page or logged in. It should be hid ...

Why isn't the input value being transmitted to the child component in Angular 5?

I have a dashboard and skills components and I am trying to pass the type from dashboard to be used in skills. However, I am encountering an error stating it is undefined. Dashboard Component: export class DashboardComponent implements OnInit { type: s ...

Configuring relative file paths within the folders in tsconfig.json

In my project, I have set up a root folder named "TypescriptProgramming" which contains the tsconfig.json file. Inside this root folder, there is another folder called "chapter1" that further includes a folder named "minfunction". The minfunction folder ho ...

Complicated connections between TypeORM and MySQL

Currently leveraging TypeORM in tandem with MySQL, my database comprises of two main Entities, namely User and Project: @Entity() class User { @PrimaryGeneratedColumn('uuid') id: string; @Column({}) name: string; } @Entity() ...

Issue encountered when compiling a React app on Windows due to identical file names with varying casing

I've been encountering compile errors in several of my files. One particular issue arises when I run the script in my package.json: "react-scripts start", causing errors when two files with similar names are located in the same directory. For instanc ...

What is the reasoning behind TypeScript's decision to permit implicit downcasting in method parameters?

Consider the following example: interface Vehicle{ mass:number } interface InspectorClass{ inspect(v:Vehicle):void } class Car implements Vehicle{ mass = 2000 wheels = 4 } class Boat implements Vehicle{ mass = 3000 sails = 2 } ...

Regular Expressions: Strategies for ensuring a secure password that meets specific criteria

Struggling to craft a regex for Angular Validators pattern on a password field with specific criteria: Minimum of 2 uppercase letters Minimum of 2 digits At least 1 special character. Currently able to validate each requirement individually (1 uppercase ...

Angular Leaflet area selection feature

Having an issue with the leaflet-area-select plugin in my Angular9 project. Whenever I try to call this.map.selectArea, VSCode gives me an error saying that property 'selectArea' does not exist on type 'Map'. How can I resolve this? I& ...

Angular throws a 404 error when making a JSONP http request

I've been incorporating Mailchimp integration into an Angular application. For using it in pure JS, I retrieved the code from the embedded form on the Mailchimp site: <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js ...

The 'Content-Type' header cannot be defined for HTTP GET requests

I am currently working on setting up my GET requests to include the specific header: Content-Type: application/json Based on information from the documentation, I need to make the following adjustment: To customize these defaults, you can add or remov ...

Is it possible for Typescript to allow extracted interfaces while excluding properties from another interface?

I've been searching for information on the specific features of this. Despite my efforts on Google, I have been unable to find the details. Any help would be greatly appreciated! interface Numbers { number: number; number2: number; number ...

Will adding additional line breaks increase the overall length of the code?

Currently, I am immersed in a project involving Angular 4 and TypeScript. Recently, I came across a video showcasing how VSCODE can enhance the code's appearance. Intrigued, I installed the prettier plugin to achieve the same effect. Running this tool ...

"Exploring the method to navigate through a nested Firebase collection linked to its parent collection

I have a forum application in development where users can ask questions and receive answers, each answer having its own 'like' feature. I am trying to access the 'likes' subcollection when viewing an answer, but I am unsure of how to do ...

What causes TypeScript to flag spread arguments within callback wrappers?

My aim is to enhance a callback function in TypeScript by wrapping it with additional logic. In order to achieve this, I have an interface called Callbacks that outlines various callback signatures. The objective is to create a wrapper function that can lo ...

Embracing Typescript version 2.7 and above allows for utilizing multiple types within a parameter, enabling developers to efficiently handle specific properties

Imagine a scenario where a ChildClass is extending the ParentClass. You can view the code on Stackblitz here. The ChildClass simply adds a public property called "brainPower": class ParentClass{ _me: string; constructor() { this._me = "I'm ...

Creating nested objects in Javascript involves adding an object inside another object

There are two objects that I have: obj1= { '201609': 52, '201610': 54, '201611': 56, metric: 'promotionsOut', careerLevelGroups: [ { '201609': 52, &a ...

Is it possible to dynamically assign a template reference variable to a newly created DOM element in TypeScript?

After creating a DOM element with this.document.createElement('h1'), I am looking to insert the element into a section tag using a template reference variable (myTRF), similar to the example below: <section> <h1 #myTRF>This is my he ...

I'm having trouble configuring the header in my Node/Express route

Using Node and the Express framework for my backend, along with React for my frontend, all coded in Typescript. The elastic search client is responsible for fetching data on the backend, but I don't believe that's where the issue lies. I'm ...

Typescript indicates that an object may be potentially null

I've hit a roadblock where I keep getting warnings that the objects might be null. After searching online and on StackOverflow, I've tried numerous solutions with no luck. My goal is to insert the text "test" into the HTML elements using their ID ...