TypeScript fails to recognize that the filtered array consists entirely of one type when using a type guard

I recently stumbled upon this code snippet in a coding playground where TypeScript is used:

export interface Page {
  heading: string;
  component: string;
  path: string;
}

export type RouteOnly = Pick<Page, 'heading' | 'path'>;


export const routes: (Page | RouteOnly)[] = [
  {
    heading: 'Home',
    path: '/home',
    component: 'A',
  },
  {
    heading: 'OSS',
    path: '/oss',
    component: 'B',
  },
  {
    heading: 'CV',
    path: '/cv'
  }
];

export function isPage(pageOrRoute: Page | RouteOnly): pageOrRoute is Page {
  return !!(pageOrRoute as Page).component;
}

const pages: Page[] = routes.filter((r) => isPage(r));

After examining the code, it appears that the pages array should only contain pages, but TypeScript is throwing an error:

Property 'component' is missing in type 'Pick' but required in type 'Page'

Answer №1

Here is a possible approach:

export interface RouteInfo {
  url: string;
  title: string;
}

// type Page = RouteInfo & { view: string };
export interface Page extends RouteInfo {
  view: string;
}

export const navigationRoutes: (Page | RouteInfo)[] = [
  {
    title: 'Main',
    url: '/main',
    view: 'FirstView',
  },
  {
    title: 'Resources',
    url: '/resources',
    view: 'SecondView',
  },
  {
    title: 'About Us',
    url: '/about'
  }
];

export function isPageComponent(arg: unknown): arg is Page {
  return ({}).hasOwnProperty.call(arg || '', 'view');
}

const pageComponents: Page[] = navigationRoutes.filter(isPageComponent);

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

The custom form input in Angular2 is throwing an error because it is trying to access the property 'name' of an

Upon switching to the latest Angular version 2 final, I encountered the following error Uncaught TypeError: Cannot read property 'name' of undefined This is my customized input import { Component, EventEmitter, Provider, forwardRef } from &a ...

Developing middleware for managing event handlers

Scenario: I am tasked with managing multiple events that necessitate an "available client". Therefore, in each event handler, my first step is to attempt to acquire an available client. If no client is available, I will send a "Service unavailable" messag ...

When trying to gather multiple parameters using @Param in a NestJS controller, the retrieved values turn out

Can someone help me understand why I am struggling to retrieve parameters using the @Param() decorators in my NestJS controller? These decorators are defined in both the @Controller() decorator argument and the @Get() argument. I am relatively new to Nest ...

How can I search multiple columns in Supabase using JavaScript for full text search functionality?

I've experimented with various symbols in an attempt to separate columns, such as ||, |, &&, and & with different spacing variations. For example .textSearch("username, title, description", "..."); .textSearch("username|title|description", "..."); U ...

Substitute Customized Interface Type Identifier

I am working on creating a versatile function interface for functor map while respecting the provided interface. In the code snippet below, my goal is to ensure that the value of mb is of type Maybe<number>, rather than the actual type Functor<num ...

Is it feasible to broaden an interface in Typescript without including a specific type?

import React from "react"; interface a_to_e { a?: string; b?: string; c?: string; d?: string; e?: string; } interface a_to_e_without_c extends a_to_e { // I want to include properties a~e except for c } function Child(props: a_to_e_without_c ...

How to display a page outside the router-outlet in angular 4

I'm currently developing an angular 4 application and I am trying to figure out how to load the login.page.ts outside of the router-outlet This is what my home.component.html file looks like: <div class="container"> <top-nav-bar></ ...

Why isn't useEffect recognizing the variable change?

Within my project, I am working with three key files: Date Component Preview Page (used to display the date component) useDateController (hook responsible for managing all things date related) In each of these files, I have included the following code sn ...

Assigning a Boolean value of false in JavaScript will result in it being evaluated as true

I'm struggling to understand why my variable continues to evaluate as true and enters the IF block, even after I specifically assign it as false. let isSetToFalse = this.model.hasQ1; console.log('type ', typeof this.model.hasQ1) //I find it ...

Utilizing Angular 2 for transforming JSON data into Angular classes

I have been working through the Angular2 getting started guide to kickstart my own application development. So far, I have managed to retrieve JSON objects from a local file and display them in angular2 templates. However, the challenge arises when the str ...

The health check URL is experiencing issues: Unable to locate any routes

I am currently developing a .net Core 2.2/Angular 8 application and recently came across the HealthCheck feature. I decided to incorporate it into my application, so here is a snippet from my Startup.cs file: using HealthChecks.UI.Client; using Mi ...

An error occurred in TSX + React: Uncaught TypeError - The property 'setState' cannot be read since it is undefined in Menu.handleClick

Currently, I am utilizing [email protected] along with react and react-dom @15.6.2. Encountering a troublesome issue that I can't seem to debug: Uncaught TypeError: Cannot read property 'setState' of undefined at Menu.handleClick. Thi ...

Retrieving the return type of generic functions stored in a map

In this unique scenario, I have a dictionary with polymorphic functions that accept the same argument but return different results: const dict = { one: { foo<A>(a: A) { return [a] as const } }, two: { foo<A>(a: A) { ...

"Implementing a unique constraint in Drizzle-orm PostgreSQL with the additional condition of deleted_at being

Is there a way to construct a table using a WHEN SQL tag? I am interested in setting up a table similar to this: "members_table", { id: serial("id").primaryKey(), email: text("email").notNull(), team_id: text(&q ...

How to Include HttpClient in an Angular Service

Looking for a service that utilizes http requests? import { Injectable } from '@angular/core'; import { Observable, of } from 'rxjs'; import { HttpClient } from '@angular/common/http'; @Injectable({ providedIn: 'root&a ...

Error in Visual Studio with Angular 2 build: 'Promise' name not found

I recently started exploring Angular2 and followed the instructions provided in this quickstart guide: https://angular.io/guide/quickstart Everything seems to be working well after running npm install, but now I want to work on it within Visual Studio usi ...

Transforming TypeScript declaration files into Kotlin syntax

Has there been any progress on converting d.ts files to Kotlin? I came across a post mentioning that Kotlin developers were working on a converter, but I am unsure about the current status. I also found this project, which seems to be using an outdated c ...

A collection of objects in TypeScript with a reference and the ability to add new objects using the

Recently, I've come across an issue in my code while working with custom objects and arrays of them. I have identified a scenario where the push() method works fine and another where it doesn't. Scenario 1 (working as expected): class MyObject{ ...

Create an entity with a field that holds a value type based on the value of another key field

Essentially, I am looking to create a customized "Pair" data type For example: type Pair<T extends Record<string, string | number>, K extends keyof T> = { field: K, value: T[K] } So, if we have: type Rabbit = { name: string, a ...

The argument labeled as 'State' cannot be assigned to a parameter labeled as 'never'

I've recently delved into using TypeScript with React. I attempted to incorporate it with the React useReducer hook, but I hit a roadblock due to an unusual error. Below is my code snippet: export interface ContractObj { company: string; ...