Ensure the object is not null with this Object type guard

Is there a way to create a type guard for an object directly in TypeScript?

I've written a function to check any input:

export function isObject(input: any) :input is Record<string,any> {
     return (input !== null) && (typeof input === 'object');
} 

However, when I try to use it, the compiler doesn't recognize my checked variable as the correct type:

const constants = {};
const haveConstantsObj = isObject(constants);

// error: Object is possibly 'null'.ts(2531)
if (haveConstantsObj && !constants.householdType) {
    console.log('hey');
}

What mistake am I making here?

Answer №1

Working with TypeScript can be a bit tricky at times.

Instead of assigning the result of isObject to a variable, try embedding it directly in the same if statement for better results.

export function isObject(input: any) :input is Record<string,any> {
     return (input !== null) && (typeof input === 'object');
} 

const constants = {};
if (isObject(constants) && !constants.householdType) {
    console.log('hey');
}

TypeScript 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

I am retrieving data from a service and passing it to a component using Angular and receiving '[object Object]'

Searching for assistance with the problem below regarding my model class. I've attempted various approaches using the .pipe.map() and importing {map} from rxjs/operators, but still encountering the error message [object Object] export class AppProfile ...

What are the steps to effectively utilize npm warnings within tslint?

After using eslint for javascript files, I am now transitioning to tslint for TypeScript linting. With eslint, I could specify some errors as NPM warnings, such as console logging. https://i.sstatic.net/BNhy6.png I realize that my "warnings" are generat ...

Challenges with incorporating asynchronously fetched data in component operations

I have encountered an issue where the data retrieved from a server in a service is available in the component's template but not in the actual code. This seems strange to me. I made the call in the ngOnInit method of my main AppComponent ngOnInit() { ...

TypeScript - the object may potentially be 'null'

Despite receiving an error message, the program is running perfectly. https://i.sstatic.net/4NQyR.jpg var video = document.querySelector('#camera-stream'), if(!navigator.getMedia){ displayErrorMessage("Your browser doesn't have su ...

What could be causing my NodeJS Backend to not retrieve the data properly?

For a current project, I am tasked with building a mobile application using Flutter for the frontend and NodeJS for the backend. To facilitate this, I have acquired a VPS from OVHcloud running Ubuntu 20.04. Following various tutorials, I set up a server as ...

Is it possible to dynamically pass a component to a generic component in React?

Currently using Angular2+ and in need of passing a content component to a generic modal component. Which Component Should Pass the Content Component? openModal() { // open the modal component const modalRef = this.modalService.open(NgbdModalCompo ...

When initially compiling Angular 5, an error (TS2339) may occur, but after a successful compilation, everything runs smoothly

In a unique scenario, I wrote code that fetches information from an API server without knowing the structure of the response fields. Once I receive the response, I need to create a form for updating the data and sending it back. To handle unknown ngModel p ...

The declaration file for module 'react/jsx-runtime' could not be located

While using material-ui in a react project with a typescript template, everything is functioning well. However, I have encountered an issue where multiple lines of code are showing red lines as the code renders. The error message being displayed is: Coul ...

Can Schema and Model/Entity Files be Decoupled in TypeORM?

Having experience with PHP (Laravel/Eloquent, Symfony/Doctrine), I am accustomed to ORMs not defining schema but making schema attributes accessible. In my previous work, I never had to use a "Model" file to manage schema as it was always handled through m ...

Upon reacting with Typescript, the window will transition to the homePage, however, it will also reset

Trying to redirect this component to the HomePage</code causes the data to restart once it reaches the home page.</p> <p>Any recommendations for an alternative to <code>window.location.href = "/HomePage"? import React, { useE ...

Switching between different types of generic functions in typescript

Is there a way to convert between these two types of generic functions: type Foo=<S>(a: S) => S type FooReturnType = ReturnType<Foo> // unknown type Bar<S> = { (a: S): S } type BarReturnType = ReturnType<Bar<string> ...

Getting a file object with v-file-input in Nuxt.js

For my Nuxt.Js apps, I utilized Vuetify.js as the UI framework. In order to obtain the file object when uploading files, I incorporated the v-file-input component from Vuetify.js and wrote the following code snippet: <template> <div> ...

Error encountered while attempting to load an image in a React component using TypeScript linting

I am currently working on a React app with Next.js where I have imported an image using the following code: import image1 from '../../../img/dummy-image-2.jpg'; Subsequently, I use the image in my app like so: <img src={image1} alt="Dumm ...

react Concealing the Card upon clicking a different location

Utilizing a combination of React and TypeScript, this component allows for the card to be toggled between shown and hidden states upon clicking on the specified div tag. However, there is a need to ensure that the card is hidden even if another area outs ...

Having trouble reading properties of undefined (specifically 'listen') during testing with Jest, Supertest, Express, Typescript

Issue: While running jest and supertest, I encounter an error before it even gets to the tests I have defined. The server works fine when using the start script, and the app is clearly defined. However, when running the test script, the app becomes undefi ...

Discovering the file system with window.resolveLocalFileSystemURL in Typescript for Ionic 3

After reviewing the documentation found on this link for the File plugin, I came across a paragraph that discusses how to add data to a log file. See the example code below: window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function (dirEntry) ...

Switch up the styling of a component by updating its properties with a switch statement

Although there is a similar question, my query has a unique requirement. I have defined the common styles for my button and implemented a function using a switch statement with different properties for various buttons across different pages. However, for ...

Angular 11 is indicating that the type 'File | null' cannot be assigned to the type 'File'

Hey there, I'm currently diving into Angular and I'm working on an Angular 11 project. My task involves uploading a CSV file, extracting the records on the client side, and saving them in a database through ASP.NET Web API. I followed a tutorial ...

Tips for saving an Angular project for offline use

I have created a basic form for a family member to use in their medical practice, and I want to make it functional offline. The form simply captures data and displays it, with no need to send or store the information anywhere. What would be the most effect ...

Navigating through ionic2 with angularjs2 using for-each loops

I developed an application using IONIC-2 Beta version and I am interested in incorporating a for-each loop. Can anyone advise if it is possible to use for each in Angular-V2? Thank you. ...