What is the best way to extract children of a specific type by filtering through their parent type in TypeScript?

What I'm looking for

In a key-value parent object, I have multiple objects with a property called namespaced of type boolean:

const obj1 = {
  namespaced: true,
  a() {}
} as const

const obj2 = {
  namespaced: false,
  b() {}
} as const

const parentObj = {
  obj1,
  obj2
} as const

I want to create a mapped type that only includes objects with namespaced set to true (and another one for false). Can this be achieved?

My approach so far

interface ParentObj {
  [name: string]: Obj
}

interface Obj {
  namespaced: boolean
}

type FilterNamespaced<P extends ParentObj> = {
  [O in keyof P]: P[O] extends { namespaced: true } ? P[O] : never
}

type FilterNotNamespaced<P extends ParentObj> = {
  [O in keyof P]: P[O] extends { namespaced: false } ? P[O] : never
}

type F1 = FilterNamespaced<typeof parentObj>

type F2 = FilterNotNamespaced<typeof parentObj>

Although the code is working to some extent, I still end up with unwanted keys like obj2 in F1 and obj1 in F2. I would like these keys to be excluded from the result.

Answer №1

To achieve this, you will require an additional layer of abstraction. Begin by filtering the keys and then selecting them from the original type. Implementing a method like KeyOfType as demonstrated in this resource will guide you towards your desired outcome:


type KeyOfType<T, U> = { [P in keyof T]: T[P] extends U ? P : never }[keyof T]

type FilterNamespaced<P extends ParentObj> = Pick<P, KeyOfType<P, { namespaced: true }>>

type FilterNotNamespaced<P extends ParentObj> = Pick<P, KeyOfType<P, { namespaced: false }>>

Play

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

Error in parsing: Unexpected token encountered. Expected a comma instead. Issue found in React with Typescript

I'm encountering a new error message that I haven't seen before... I've checked my code thoroughly and it seems to be correct, yet the error persists. Here is my code snippet: interface AuthState { token: string; user: User; } interfac ...

Export multiple variables at once

Within TypeScript, I have Class1 defined in class.ts, along with some functions from helper.ts and variables from variables.ts: For instance, the content of variables.ts is as follows: export const test1 = 'test1'; export const test2 = 0; expor ...

I am trying to figure out how to dynamically set the deployUrl during runtime in Angular

When working with Angular, the definition of "webpack_public_path" or "webpack_require.p" for a project can be done in multiple ways: By setting the deployUrl in the .angular-cli.json file By adding --deployUrl "some/path" to the "ng build" command line ...

I'm having trouble displaying the saved percentage value in an angular material mat select component

When I use the mat-form-field and mat-option to list numbers 1-100, the saved value is not displaying in the dropdown after saving. <mat-form-field class="full-wid" appearance="outline"> <mat-label>Percentage 1 (%)</mat-la ...

A versatile method for transforming enums into arrays that can handle null values

Looking for a simpler way to create a TypeScript function that converts an enum to an array, including support for null values. Here's an example of what I'm trying to achieve: enum Color { RED = "Red", GREEN = "Green&qu ...

Struggling to retrieve the value of a text field in Angular with Typescript

In the Angular UI page, I have two types of requests that I need to fetch and pass to the app.component.ts file in order to make a REST client call through the HTML page. Request 1: Endpoint: (GET call) http://localhost:8081/api/products?productId=7e130 ...

A TypeScript Record that allows for inferable value types

How can I construct a map that enforces the presence of all keys while still allowing the inference of the types of its values? If I have certain keys, for example: type State = "OPEN" | "CLOSED"; Method 1: using an untyped object con ...

typescript tips for incorporating nested types in inheritance

I currently have a specific data structure. type Deposit { num1: number; num2: number; } type Nice { num: number; deposit: Deposit; } As of now, I am using the Nice type, but I wish to enhance it by adding more fields to its deposit. Ultima ...

Unlock the power of the multiselect dropdown component in MUI with direct access

I'm intrigued by the multi-select capabilities of the MUI Select component when using the multiple=true option. However, rather than having a traditional dropdown menu, I want to integrate the selection options directly into a div on the page. I prefe ...

What prevents us from returning Observable.of(false) in the catch block within the canActivate function?

In order to protect certain routes (admin), I utilize the canActivate feature. In this scenario, I employ an authGuard class/function: The issue arises when attempting to return an observable of boolean using: return Observable.of(false);. This approach d ...

Resolving TypeScript errors when using the Mongoose $push method

It appears that a recent package upgrade involving mongoose or @types/mongoose is now triggering new typescript errors related to mongoose $push, $pull, $addToSet, and $each operators. For instance: await User.findByIdAndUpdate(request.user._id, { $ ...

Using Typescript to typecast in D3.js

Utilizing the D3 graph example available here. I've defined my data object as shown below: interface ID3Data { age: string, population: number } const data: ID3Data[] = [ { age: "<5", population: 2704659 }, { age: "5-13", population: 4499 ...

Performing actions simultaneously with Angular 2 directives

My custom directive is designed to prevent a double click on the submit button: import { Directive, Component, OnInit, AfterViewInit, OnChanges, SimpleChanges, HostListener, ElementRef, Input, HostBinding } from '@angular/core'; @Directive({ ...

I'm confused about this CallbackRouteError with the provider named "credentials". Can someone please explain?

I can't seem to resolve this error after searching extensively on the web. For more information, visit [auth][error] CallbackRouteError: For more details, please visit https://errors.authjs.dev#callbackrouteerror [auth][cause]: Error at Module.callb ...

Using TypeScript to implement Angular Draggable functionality within an ng-template

Sorry if this question has been asked before, but I couldn't find any information. I am trying to create a Bootstrap Modal popup with a form inside and I want it to be draggable. I have tried using a simple button to display an ng-template on click, b ...

Are you looking to resolve TypeScript warnings related to imports managed by Webpack loaders?

Setting up a new project with Svelte, Webpack, and TypeScript based on this template. Ran the scripts/setupTypeScript.js script to switch to TypeScript after initial setup. Encountering errors in VSCode and TypeScript when importing non-TypeScript files: ...

How do I retrieve the value of a dxi-item in TypeScript with Angular and Devextreme?

One of the challenges I am facing is related to a Data Grid that has editing capabilities in popup mode. Within this grid, there are two data fields - password and confirm password - which I would like to validate to ensure they match. However, I am strugg ...

Unable to bind to ngModel as it returned as "undefined" in Angular 8

Whenever I bind a property to ngModel, it consistently returns undefined <div> <input type="radio" name="input-alumni" id="input-alumni-2" value="true" [(ngModel) ...

Experiencing constant errors with axios requests in my MERN Stack project using a Typescript Webpack setup

Hey there, I'm in need of some help! I've been working on a MERN Stack project and have set up Webpack and Babel from scratch on the frontend. However, every time I send a request to my Node Server, I keep getting an error message back. Can anyon ...

What is the process for triggering property decorators during runtime?

Wondering about dynamically invoking a property decorator at runtime. If we take a look at the code snippet below: function PropertyDecorator( target: Object, // The prototype of the class propertyKey: string | symbol // The name of th ...