TypeScript may be throwing an error due to a peculiar object possibly being "null"

In my function, I am checking whether an unknown value resembles a Date object:

function looksLikeDate(obj: unknown): obj is { year: unknown; month: unknown; day: unknown } {
    return (
        obj !== null && typeof obj === "object" && "year" in obj && "month" in obj && "day" in obj
    );
}

However, I encounter an error related to the "year" in obj part of the code:

The object could possibly be 'null'. (2531)

Interestingly, when I interchange obj !== null and

typeof obj === "object"
, the error disappears: TS Playground Link

Doesn't this seem peculiar? Can someone provide an explanation for this behavior?

Answer №1

Is the typeof null really 'object'?

It's interesting to note that when you do the typeof check after confirming that a variable is null, the object can still be considered null according to the TypeScript compiler.

These type guards can be quite delicate in this regard. For instance, in your case, the statement typeof obj === 'object' actually changed the type from "not null" to object or null.

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

Getting the Angular component class reference within a triggered Highcharts selection event callback - what's the best approach?

It seems like I'm facing a common javascript closure issue, but let me illustrate it with a specific example as I'm struggling to grasp it in an Angular context. In my Angular component, I'm using the Highcharts library to visualize data. W ...

Transitioning to TypeScript has brought the promise of imports returning once again

I've been facing some challenges while migrating my extensive project to TypeScript, particularly with handling imports. Being relatively new to programming, I'm unsure if my previous approach was considered bad practice. Previously, I organized ...

Ways to fix the error: The _AppComponent component is not designated as standalone, however, Angular anticipates having a standalone component here

Currently, I am in the process of upgrading my project from Angular 9.1 to Angular 18.1. However, I am facing a compilation error that reads: NG0907: The _AppComponent component is not marked as standalone, but Angular expects to have a standalone compone ...

Discover the data type of a class attribute's accessor methods in TypeScript

Since TypeScript 4.3 introduced the ability for class properties to have getters and setters of different types since 4.3, I am unsure how to correctly retrieve the types of a property's getter and setter. === Since a class property is treated as a ...

I am currently working on creating my website on CloudFlare with the help of React.JS

Struggling with a website build issue while using the Git repo on Cloudflare. Despite attempting various solutions like deleting yarn.lock, running yarn cache clean -all, and then yarn install, I keep encountering the same error. Since I am relatively new ...

Limiting functional component re-renders to only occur when certain states change

Is there a way to make a component re-render only when a specific state in that component changes, instead of re-rendering with every state change? Here is an example code snippet: suppose I have a component with three states and I want it to re-render on ...

Universal loading screen across all components

I am currently implementing a loading screen for this component in conjunction with the fetch method. My concern is whether I will need to replicate the same loading logic used in the example for every component that utilizes the fetch() method, or if the ...

What type of event is triggered by the "change" event in Vue.Draggable?

Trying to determine the type of a change event from Vue.Draggable, as per the documentation provided on https://github.com/SortableJS/Vue.Draggable Struggling to find its definition, the event seems to have a specific payload according to the documentati ...

The TypeScript elusive bug is making me lose my mind: Struggling to exclude types using control statements

I encountered a recurring error that I managed to narrow down to a specific scenario which only occasionally replicates on the TypeScript Playground, but consistently fails when running tsc locally. type Result = { success: true, value: string, } | { ...

"An error occurs when attempting to access "this" in a static method as it

Just diving into the world of React and Typescript and currently exploring React hooks. Encountered a problem that's leaving me scratching my head. Here's the hook I'm using to fetch data: export const useFetch = <T>( fetchFunc: ( ...

After updating Bootstrap, the build task encountered an error when it was unable to locate the node.exe needed to run the TypeScript compiler

After developing an ASP.Net MVC web application that was almost completed, I decided to update Bootstrap using the NuGet package manager to the latest stable version 4.3.1. The update process went smoothly, but unfortunately, I encountered errors after mig ...

Can the child component ensure that the Context value is not null?

In the process of developing a Next.js/React application with TypeScript, I've implemented a UserContext in pages/_app.js that supplies a user: User | null object to all child components. Additionally, there's a ProtectedRoute component designed ...

Showing Firebase messages in a NativeScript ListView in an asynchronous manner

I am currently struggling to display asynchronous messages in a ListView using data fetched from Firebase through the popular NativeScript Plugin. While I have successfully initialized, logged in, and received the messages, I'm facing challenges in ge ...

Redux, React, and Typescript work together seamlessly to create a dynamic application that utilizes the Connect function to

I am currently facing an issue with the following code example: import * as React from "react"; import { connect } from 'react-redux'; interface IMessage { message : string; } class SayMessage extends React.Component<IMessage, {}>{ ...

Can you identify the specific error type that occurs in the onError function of react-query's MutationCache when using Typescript

Can someone help me with identifying the type of error in react-query MutationCache onError function when using Typescript? I also need guidance on how to override the type so that I can access and use the fullMessage from the data. const queryClient = new ...

Transitioning from Global Namespace in JavaScript to TypeScript: A seamless migration journey

I currently have a collection of files like: library0.js library1.js ... libraryn.js Each file contributes to the creation of a global object known as "MY_GLOBAL" similarly to this example: library0.js // Ensure the MY_GLOBAL namespace is available if ...

Retrieving document attributes from a Mongoose Model with the help of Typescript

Incorporating Typescript with Mongoose, my aim is to retrieve properties from a Model. Taking the illustrated UserModel as an example import mongoose, { Schema } from 'mongoose'; const userSchema: Schema = new mongoose.Schema({ _id: mongoos ...

What is the best way to combine two arrays of objects with varying values for the same key, and add a new object to the mix?

I have two arrays: arr1 = [ { "OwnershipNumber": 0, "ID": null, "Name": "Contractor LLC", "ContrEmployeeTypeId": 0, "ContactEmail": "", "ContactPhone": "", "VeteranEmployeeMilitaryAffiliation": "", "SocialSecurityNumber": ...

Arrange a JSON response in descending order and filter out specific values

Currently, I'm encountering a challenge when trying to extract a specific attribute from my JSON response. The issue arises when I attempt to sort the results based on the `percentage_match` in descending order. Once sorted, my goal is to create an ar ...

No results returned by Mongoose/MongoDB GeoJSON query

I have a Schema (Tour) which includes a GeoJSON Point type property called location. location: { type: { type: String, enum: ['Point'], required: true }, coordinates: { type: [Number], required: true ...