Sort attributes by the type of property

Is there a way to create a customized type by extracting specific properties from a generic type?

class Test {
  value1!: Date
  value2!: number
  value3!: Date
  value4!: string
}
type FilterProperties<T, TFieldType> = //looking for a solution to select fields of the type TFieldType only
const onlyDates = {} as FilterProperties<Test, Date>

FilterProperties<Test, Date>
should ideally contain only the properties value1 and value3.

I attempted using Extract and Pick, but they operate based on keys rather than types.

Answer №1

Here is a useful technique you can apply:

class Example {
  item1!: Date
  item2!: number
  item3!: Date
  item4!: string
}

type SelectItems<T, TFieldType> = {
    [K in keyof T as T[K] extends TFieldType ? K : never]: T[K]
}

type C = SelectItems<Example, Date>
/*
type C = {
    item1: Date;
    item3: Date;
}
*/

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

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) ...

Unexpected behavior: Promise.catch() fails to catch exception in AngularJS unit test

During the process of writing Jasmine unit tests for my Typescript app and running them via Resharper, I encountered an issue with executing an action when the handler throws an exception: describe("Q Service Test", () => { var q: ng.IQService; ...

Exploring the use of generic types in TypeScript interfaces

I have the following two interfaces: export interface TestSchema<S> { data: S; description: string; } export type someType = 'option1' | 'option2'; export interface AnotherInterface { primary: string; secondary: someType; ...

Exploring Angular 2's nested navigation using the latest router technology

Is there a way to implement nested navigation in Angular? I had this functionality with the previous router setup. { path: '/admin/...', component: AdminLayoutComponent } It seems that since rc1 of angular2, this feature is no longer supported. ...

The 'payload' property is not found within the 'Actions' type

I recently started using TypeScript and Visual Studio Code. I encountered the following issue: *[ts] Property 'payload' does not exist on type 'Actions'. This is my code: action.ts file: import { Action } from '@ngrx/store&apos ...

How can we design a Protobuf structure for a map that contains an array of objects as the value?

I need help with encoding a map in a protobuf format. Here is an example of the map: const newVisMap = new Map<number, IOutput[]>(); The map contains an array of objects that share a common interface, as shown below (with one optional property): int ...

The 'ref' attribute is not found within the 'IntrinsicAttributes' type

I'm currently working on a TypeScript project using React. Although the code is functional, I keep encountering compiler errors with my ref. Here's an example of the code: Firstly, there's a higher-order component that handles errors: expor ...

Leveraging Ionic 2 with Moment JS for Enhanced TimeZones

I am currently working on integrating moment.js with typescript. I have executed the following commands: npm install moment-timezone --save npm install @types/moment @types/moment-timezone --save However, when I use the formattime function, it appears th ...

storing information in localStorage using react-big-calendar

Incorporating react-big-calendar into my project, I encountered a problem where the events in the calendar would disappear upon page refresh despite saving them in localStorage. I had planned to store the events using localStorage and retrieve them later, ...

Starting a fresh Angular project yields a series of NPM warnings, notably one that mentions skipping an optional dependency with the message: "npm

Upon creating a new Angular project, I encounter warning messages from NPM: npm WARN optional SKIPPING OPTIONAL DEPENDENCY: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="68e01b0d1e0d061c7518d7">[email protecte ...

Errors are not displayed or validated when a FormControl is disabled in Angular 4

My FormControl is connected to an input element. <input matInput [formControl]="nameControl"> This setup looks like the following during initialization: this.nameControl = new FormControl({value: initValue, disabled: true}, [Validators.required, U ...

`I'm having difficulty transferring the project to Typescript paths`

I posted a question earlier today about using paths in TypeScript. Now I'm attempting to apply this specific project utilizing that method. My first step is cloning it: git clone <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cf ...

How can I select just one element to be impacted by a click event when using map in TypeScript?

Currently, I'm facing an issue where I want to change the icon of a button when it's selected. The problem is that using map affects all buttons even if only one is selected. // ... const [clicked, setClicked] = useState(false); <Button sta ...

Best practice for saving a User object to the Request in a Nest.js middleware

Currently, in my nest.js application, I have implemented a middleware to authenticate Firebase tokens and map the user_id to my database. Within this middleware, I retrieve the user_id from Firebase, fetch the corresponding User object from the database, a ...

What is the method for including a dynamic image within the 'startAdornment' of MUI's Autocomplete component?

I'm currently utilizing MUI's autocomplete component to showcase some of my objects as recommendations. Everything is functioning correctly, however, I am attempting to include an avatar as a start adornment within the textfield (inside renderInp ...

React with Typescript - cannot be expressed as a function

I am currently exploring ReactJS and Typescript. While trying to authenticate a user using the methods below, I encountered the following error message: Unhandled Rejection (TypeError): auth.authenticate is not a function onSubmit src/components/Login/ind ...

Steps for reinstalling TypeScript

I had installed TypeScript through npm a while back Initially, it was working fine but turned out to be outdated Trying to upgrade it with npm ended up breaking everything. Is there any way to do a fresh installation? Here are the steps I took: Philip Sm ...

Issue encountered with TypeORM and MySQL: Unable to delete or update a parent row due to a foreign key constraint failure

I have established an entity relationship between comments and posts with a _many-to-one_ connection. The technologies I am utilizing are typeorm and typegraphql Below is my post entity: @ObjectType() @Entity() export class Post extends BaseEntity { con ...

How to execute a function in a child component that is declared in the parent component using Angular

Is anyone able to help me with an issue I am facing in my Angular project? I have two components, 'app' and 'child'. Within the child component, I have a button that calls a function defined in the app component. However, this setup is ...

The PhotoService (?) is facing difficulties in resolving dependencies according to Nest

Just started diving into Nest.js and encountering an issue right after setting up a service: Nest is throwing an error while trying to resolve dependencies of the PhotoService (?). Make sure that [0] argument is accessible in the current context. I' ...