Limit the usage of typescript to ensure that references to properties of 'any' object are verified

I'm facing a situation where I have a JS object called myObject, and it is of type any. Unfortunately, I cannot change the type as it's coming from a library.

The issue I encounter is that when trying to access a property from myObject, TypeScript does not throw any errors since its type is any. However, there is a possibility that myObject could be undefined, leading to a crash.

Is there a way to make TypeScript generate an error in such cases?

For instance:

console.log(myObject.myProperty) // <-- this will cause a crash if myObject is undefined.

What I desire:

console.log(myObject.myProperty) // <-- TypeScript shows error
console.log(myObject?.myProperty) // <-- TypeScript doesn't show error

Is there a tsconfig setting to modify this behavior?


I'm specifically not interested in using type unknown for resolving this.

Answer №1

Unfortunately, TypeScript does not offer support for a stricter interpretation of the `any` type where member access is restricted unless it is deemed safe. There hasn't been any formal request for this feature either. While there was a proposal for `--strictAny`, it was eventually closed in microsoft/TypeScript#24737, with the reason being that adding extra complexity to the `any` type didn't seem warranted, especially given that `any` is often used intentionally to disable type checking in certain real-world scenarios.

Instead of waiting for TypeScript to introduce such functionality, you could consider utilizing a linter like TypeScript ESLint. The `no-unsafe-member-access` rule specifically prohibits unsafe member access on variables typed as `any`. However, be aware that this may lead to unwanted errors even in situations where proper type checking has been implemented, making it more restrictive than desired.

declare const myObject: any;
myObject.myProperty // warning: unsafe access 😊
myObject?.myProperty // warning: unsafe access ☹

If you find yourself in this situation, one workaround could involve copying the value to a variable of a non-`any` type:

type MyAny = { [k: string]: any } | undefined | null;
const _myObject: MyAny = myObject
_myObject.myProperty; // error
_myObject?.myProperty; // okay

Alternatively, you could create a type checking function to narrow down the `any` type to a more safely indexable type:

function nonNullish(x: any): x is { [k: string]: any } {
  return x != null;
}
if (nonNullish(myObject)) {
  myObject.myProperty // okay
}

Another approach could involve discussing with the typings provider for the library to emphasize that using `any` might be too loose of a type, especially if the value could potentially be `undefined` or `null` at runtime. If that's not an option, then perhaps accepting and monitoring potential issues until they actually occur might be the way to go.

TS-ESLint Playground link to code

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

Sending data to a parent component from a popup window in Angular Material using a button click while the window is still open

How can I retrieve data from an Angular Material Dialog Box and send it to the Parent component? I am able to access data after the dialog box is closed. However, I am wondering if there is a way to retrieve data while the dialog box is still open, especi ...

Resolving NestJS Custom Startup Dependencies

In my setup, I have a factory responsible for resolving redis connections: import {RedisClient} from "redis"; export const RedisProvider = { provide: 'RedisToken', useFactory: async () => { return new Promise((resolve, reject ...

Inferring types in a generic function with multiple parameters

In my attempt to configure a generic with the parameter serving as the key of another object, I have found success using extends keyof when both types are provided as parameters to the function. However, I encountered an issue when the type that provides ...

The Strapi plugin seems to be encountering an issue as the API is not reachable, leading to a

In an attempt to create a custom API in Strapi backend, I developed a plugin called "test" for testing purposes. However, when trying to access the test response in Postman, it displays a 404 error stating that it is not accessible. Let me provide you wit ...

Incorporate a JavaScript script into an Angular 9 application

I have been experiencing issues trying to add a script.js file to angular.json and use it in one component. Adding a script tag directly to my HTML file is not the ideal solution. Can someone suggest an alternative approach or point out what I may be missi ...

The error states that the type '() => string | JSX.Element' cannot be assigned to the type 'FC<{}>'

Can someone help me with this error I'm encountering? I am fairly new to typescript, so I assume it has something to do with that. Below is the code snippet in question: Any guidance would be greatly appreciated. const Pizzas: React.FC = () => { ...

Refreshing functional component upon change in property of different class [MVVM]

I've been tasked with incorporating MVVM into React for a class assignment. To achieve this, I've opted to use functional components for the view and TypeScript classes for the ViewModel. However, despite successfully updating properties in the V ...

Change the background color of a span element dynamically

I am currently working on implementing dynamic background coloring for a span tag in my Angular view that displays document types. The code snippet provided is as follows: <mat-card *ngFor="let record of records"> <span class="doc ...

Utilizing Global Variables and Passing Values in Ionic 3

It seems like my issue is rather straightforward, but there is definitely something eluding me. After logging in, I need to store a TOKEN for HTTP requests in a global variable. Upon successful login, the HTTP get method returns an object with the HTTP co ...

"NameService is not provided in Angular, please check your module

I've been struggling with loading a class into my Angular component. I've spent quite some time trying to figure out the solution, even attempting to consolidate everything into a single file. Here is what I have: Application.ts /// <referenc ...

Guide to utilizing vue-twemoji-picker in TypeScript programming?

Has anyone encountered this issue when trying to use vue-twemoji-picker in a Vue + TypeScript project? I keep receiving the following error message. How can I fix this? 7:31 Could not find a declaration file for module '@kevinfaguiar/vue-twemoji-picke ...

Encountering issues with HTML loading interpolation before constructor in TypeScript

I am currently working on a project using Angular 6 and encountering some challenges. Here is the issue at hand: I am facing an error in the HTML Console, which occurs after reloading the page. The error message indicates that the variable "atual" is unde ...

Angular 2 Date Input failing to bind to date input value

Having an issue with setting up a form as the Date input in my HTML is not binding to the object's date value, even though I am using [(ngModel)] Here is the HTML code snippet: <input type='date' #myDate [(ngModel)]='demoUser.date& ...

TypeScript: Type narrowing issue when deconstructing an array within a function

I am working with an object that has a const assertion: const foo = { bar: ['a', 'b'], } as const; My objective is to create a function that can update the bar array and accurately infer the new type. I have successfully achieved th ...

I'm new to Angular, so could you please explain this to me? I'm trying to understand the concept of `private todoItems: TodoItem[] = []`. I know `TodoItem` is an array that

//This pertains to the todoList class// The property name is todoItems, which is an array of TodoItem objects fetched from the TodoItem file. I am unable to make it private using "private todoItems: TodoItem[] = []," is this because of Dependency Injectio ...

Incorporate matTooltip dynamically into text for targeted keywords

I'm currently tackling a challenge in my personal Angular project that utilizes Angular Material. I'm struggling to find a solution for the following issue: For instance, I have a lengthy text passage like this: When you take the Dodge action, ...

Difficulty encountered when utilizing stockfish.js in conjunction with TypeScript

After executing npm install stockfish, I created a simple file named getBestMove.ts which contains the following code: import stockfish from 'stockfish'; const fen = '3r1r1k/pp2Nqbp/3Rb2p/2P1pp2/7P/N1P3P1/PP2QP2/R3K3 w - - 2 30' inter ...

Loading dynamic components asynchronously in Vue 3 allows for improved performance and enhanced user experience

My goal is to dynamically display components based on their type. Here's how I'm approaching it: I have several similar components that should show different content depending on their type. Using the defineAsyncComponent method, I can easily im ...

Building an instance using an object and an array with Vue.js 2.0

I am working with an array and an object created in Vue.js, and my goal is to combine them into a single 'selection' array following this format: selection[ {food: Chicken, quantity: 3}, {food: Rice, quantity: 2}, {food: Pasta, quantity: 1} ]; ...

Is there a way to halt the current traversal of visitEachChild in TypeScript Transformer API?

While navigating through each child node of a parent node using visitEachChild, is there a way to stop the process when I no longer wish to visit the subsequent child nodes? For example: Parent node Node 1 Node 2 <-- My target point. Node 3 Node 4 Nod ...