The 'in' operator is unable to find 'colour' within true (function return type)

Here's the TypeScript code I'm working with:

let a: unknown = true;

if(hasColour(a)) {
    console.log(a.colour);  // Using a.colour after confirming a has the colour property
}

I've created a function to check if the color property exists:

function hasColour (obj: any) : boolean {
    return !!obj &&
    "colour" in obj &&
    typeof obj == "object" 

}  

An error is popping up saying:

Cannot use 'in' operator to search for 'colour' in true.

To fix this, instead of specifying boolean as the return type, specify: obj is { colour: string } like so:

function hasColour (obj: any) : obj is { colour: string } {
    return !!obj &&
    "colour" in obj &&
    typeof obj == "object" 

}  

Why does this work? Shouldn't hasColour return a true/false? Why does it work with obj is { colour: string } as a return type?

Answer №1

Explaining the distinction between...

function hasColour (obj: any) : boolean {
    return !!obj &&
    typeof obj == "object" &&
    "colour" in obj
}  

...and...

function hasColour (obj: any) : obj is { colour: string } {
    return !!obj &&
    typeof obj == "object" &&
    "colour" in obj
}

...lies in the fact that the second version functions as a type guard. By employing a type guard, your unknown type will be narrowed down to { colour: string }, and within the if statement where the type guard is used, the compiler will ensure the presence of the colour property.

On the other hand, the first version simply returns a boolean. The compiler cannot infer anything from it, as it lacks information regarding the type check being performed within the function. With a type guard, you explicitly instruct the compiler to make an assertion about the type.

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

Issue with uploading video files using ng2-file-upload in Angular7 and ASP .Net Core 2.1

While working on my project, I encountered an issue with uploading video files using ng2-file-upload to the server. The photo upload functionality is working fine, but when attempting to upload a video file larger than 27MB, the process gets canceled autom ...

Error Handling in Angular2 MVC 4 Project Route Issues

Here is the structure of my Mvc 4 Project with angular 2 implemented: Solution 'Angular2Starter' |-- angular2Starter | `-- Controllers | `-- HomeController.cs |-- src | |-- app | | |-- home | | | |-- home.component.ts | ...

Retrieve a specific element from an array list

Hey everyone, I'm facing a problem in my application where I need to extract a specific value from my array and display it in a table for users to see. Check out the code snippet below: Here's my mock data: { "Data": "2020-0 ...

Leveraging global attributes beyond Vue components - Vue 3

I have created custom service instances in main.ts app.config.globalProperties.$service1 = new Service1(); app.config.globalProperties.$service2 = new Service2(); While I can use these instances inside Vue components, I also want to be able to utilize the ...

typescript: declaring types in a separate JavaScript file

Imagine you have a JavaScript library that exports some types for use (let's call it js1.js). You also have some TypeScript code sitting in a <script type="module"> tag that you want to use these types with (let's say ts1.ts). To make this ...

"Implementing an abstract method in a class by overloading it with a generic type that

// Greetings from the TypeScript Playground, a platform where you can experiment with TypeScript code. type Constructor<T> = new (...args: any[]) => T; class ServiceChecklistResponse { } class AnotherModel { } abstract class AbstractView { ...

Customize nestjs/crud response

For this particular project, I am utilizing the Nest framework along with the nestjs/crud library. Unfortunately, I have encountered an issue where I am unable to override the createOneBase function in order to return a personalized response for a person e ...

I encountered difficulties connecting mongoose to my local MongoDB server

Hello Everyone! Currently, I am in the process of linking my node.js project to mongodb. Initially, everything worked smoothly when I used mongodb atlas. However, when I attempted to connect it using mongodb compass, I faced some issues and nothing seemed ...

What are the benefits of using default ES module properties for exporting/importing compared to named module properties?

Currently studying the Material UI documentation, I came across this statement: It is noted in the example above that we used: import RaisedButton from 'material-ui/RaisedButton'; instead of import {RaisedButton} from 'material-ui&apo ...

How to conceal the side navigation bar on specific pages or components within an Angular application

Currently immersed in developing a web application with Jhipster and Angular. I've managed to set up a side navbar along with a top navbar on every page. However, I'm struggling to hide the side navbar on specific pages and could use some guidanc ...

Ways to retrieve a value from outside the Angular subscribe block

Custom Template <div class="row" *ngFor="let otc of this.jsonData;index as j"> <div> <table class="table table-striped table-fixed"> <tr *ngFor="let opc of this.winServiceInfo ...

What are the steps to integrate TypeScript into JavaScript code?

How can I import a TypeScript class in a Node CommonJS JavaScript file? When using mongoose in my TypeScript code, I typically do the following: // user.model.ts export const UserModel = model<User>('User', schema); In my JavaScript code: ...

Guide on changing the color of the selected item in mat-nav-list within angular 6

Recently diving into Angular 6 and facing an issue with my mat-toolbar integrated with mat-sidenav. Everything seems to be functioning fine, but I'm looking to customize the color for the active item in the side nav menu. Currently, all items have a ...

Gradle synchronization in IntelliJ causing missing folders in WAR Artifact

Currently, I am working on a Spring MVC application that incorporates TypeScript. The TypeScript code is transpiled using a Gradle task from the directory src/main/ts to build/ts. Subsequently, the resulting JavaScript files are added to the WAR file usin ...

When working with the Sequelize-Typescript One To Many Association and Repository, a situation may arise where the query returns only one child entity even though there are multiple

Dealing with Sequelize-Typescript, I recently encountered the one-to-many association involving "Album" and "Photos" entities. Each "Album" can have multiple "Photos". Below are the entity codes for reference: Album.ts ` @Table({ timestamps: true, de ...

Ways to reveal heavily nested components when the Angular change detector fails to detect them

A particular component called Grid has been implemented with the following template: <div *ngFor="let row of item.rows"> <div *ngFor="let col of row.cols"> <div *ngFor="let grid of col.items"> < ...

Angular Ahead-of-Time (AOT) compilation causes multiple route definitions to be

Having a bit of trouble configuring ahead-of-time compilation for my lazy-loaded Angular app. The lazy-loaded routes are specified in the app.routes.ts file, which is imported by app.module.ts. Running ngc results in the content of app.routes.ts being mer ...

Converting types to "any" and encountering the error message "There are two distinct types with the same name, but they are not related."

I am encountering some challenges while trying to use an NPM module that I developed along with its Typescript typings in another application. To simplify the examples, I will omit properties that are not relevant to the issue at hand. Within my module&ap ...

What is the best way to customize a button component's className when importing it into another component?

Looking to customize a button based on the specific page it's imported on? Let's dive into my button component code: import React from "react"; import "./Button.css"; export interface Props { // List of props here } // Button component def ...

Tips for differentiating between elements with identical values in an HTML datalist using Angular

My boss is insisting that I use a datalist in our website interface to select an employee, even though there's no way to determine if the user typed in the name or picked from the list. The challenge is that the list must only display full names, but ...