Omit functions from category

This question reminds me of another question I came across, but it's not quite the same and I'm still struggling to figure it out.

Basically, I need to duplicate a data structure but remove all the methods from it.

interface XYZ {
  x: number;
  y: string;
  z(): void;
}

So in this case, I want to exclude the method z and end up with:

interface XY {
  x: number;
  y: string;
}

I am aware that I can use the Omit utility type like this:

type OmitZ = Omit<XYZ, "z">;

However, I actually want to omit based on property type rather than key string. Is there a way to achieve this?

Answer №1

Give this a shot:


const ExcludeFunctions = <T>(obj: T) => {
  const newObj = {} as { [K in keyof T]: T[K] extends Function ? never : K };
  
  for (const key in obj) {
    if (!(obj[key] instanceof Function)) {
      newObj[key] = obj[key];
    }
  }

  return newObj;
};

const result = ExcludeFunctions({ name: "John", age: 30, sayHello: () => console.log("Hello") });

console.log(result); // Output: { name: "John", age: 30 }

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

Creating a dynamic array in an Angular 2 service for real-time changes monitoring by a component

I am facing an issue where my NotificationsBellComponent is not receiving changes to the array in the service even though the _LocalStorageService is returning data correctly. Q) How can I ensure that my component receives updates when the service collect ...

Serverless-offline is unable to identify the GraphQL handler as a valid function

While attempting to transition my serverless nodejs graphql api to utilize typescript, I encountered an error in which serverless indicated that the graphql handler is not recognized as a function. The following error message was generated: Error: Server ...

Utilizing Angular 4 to dynamically render a template stored in a string variable

Is it possible to dynamically render HTML using a string variable in Angular4? sample.component.ts let stringTemplate = "<div><p>I should be rendered as a HTML<br></p></div>"; The contents of the sample.component.html s ...

Utilize Firebase for Playwright to efficiently implement 'State Reuse' and 'Authentication Reuse'

In my testing environment, I want to eliminate the need for repeated login actions in each test run. My approach involves implementing 'Re-use state' and 'Re-use Authentication', but I've encountered a challenge with Firebase using ...

Experiencing difficulty in transferring array information from a parent component to a child component within an

I'm currently working on a task where I need to pass data from a parent component to a child component. The data consists of an array that is nested within another array. parent.component.html <div *ngFor="let parent of parentArray; index as ...

Moving from Http to HttpClient in Angular4Changeover your Angular4

I recently migrated my Angular app to use the new HttpClient, but I'm encountering some challenges in achieving the same results as before with Http. Can anyone help me out? Here's what I was doing with Http: getAll() { return this.http.get ...

Is it necessary for the React generic type prop to be an extension of another type

I have recently started using TypeScript and I am facing a confusion regarding passing generic types into my higher-order component (HOC). My objective is to pass the component props as a generic type in order to have the Component with those specific type ...

The specified type 'Observable<{}' cannot be assigned to the type 'Observable<HttpEvent<any>>'

After successfully migrating from angular 4 to angular 5, I encountered an error in my interceptor related to token refreshing. The code snippet below showcases how I intercept all requests and handle token refreshing upon receiving a 401 error: import { ...

A guide on simulating childprocess.exec in TypeScript

export function executeCommandPromise(file: string, command: string) { return new Promise((resolve, reject) => { exec(command, { cwd: `${file}` }, (error: ExecException | null, stdout: string, stderr: string) => { if (error) { con ...

Facing difficulty in accessing mongoose schema static method in TypeScript

I am currently facing an issue where I have a method called "findByToken()" defined in the model and implemented as a static method in the userSchema. However, in another part of my application, I am unable to access the method using: User.findByToken(tok ...

The conflict arises when importing between baseUrl and node_modules

I am currently working on a TypeScript project with a specific configuration setup. The partial contents of my tsconfig.json file are as follows: { "compilerOptions": { "module": "commonjs", "baseUrl": &quo ...

Node.js is known for automatically adding double quotes to strings. However, is there a way to eliminate them?

After creating a unit test, I noticed that both logics I used led to the same issue. Logic 1: describe('aresFileCopier', () => { test('log error', async () => { await registerDB('ares-test', { client: ' ...

Mapping JSON data from an array with multiple properties

Here is a JSON object that I have: obj = { "api": "1.0.0", "info": { "title": "Events", "version": "v1", "description": "Set of events" }, "topics": { "cust.created.v1": { "subscribe": { ...

The meaning behind a textual representation as a specific type of data

This snippet is extracted from the file lib.es2015.symbol.wellknown.d.ts interface Promise<T> { readonly [Symbol.toStringTag]: "Promise"; } The concept of readonly seems clear, and the notation [Symbol.toStringTag] likely refers to "'toStr ...

Animated drop-down menu in Angular 4

I recently came across this design on web.whatsapp.com https://i.stack.imgur.com/ZnhtR.png Are there any Angular packages available to achieve a dropdown menu with the same appearance? If not, how can I create it using CSS? ...

"Exploring the world of 3rd party libraries in Angular2 with Typescript and Webpack

I've begun working on a fantastic seed project that can be found at: https://github.com/AngularClass/angular2-webpack-starter However, I've encountered an issue with integrating third-party modules. Can anyone offer guidance on how to properly a ...

Utilizing TypeScript with Svelte Components

I've been struggling to implement <svelte:component /> with Typescript without success. Here's my current attempt: Presentation.svelte <script lang="ts"> export let slides; </script> {#each slides as slide} & ...

The property is not found within the type, yet the property does indeed exist

I'm baffled by the error being thrown by TypeScript interface SendMessageAction { type: 1; } interface DeleteMessageAction { type: 2; idBlock:string; } type ChatActionTypes = SendMessageAction | DeleteMessageAction; const CounterReduc ...

Unable to store object data within an Angular component

This is a sample component class: export class AppComponent { categories = { country: [], author: [] } constructor(){} getOptions(options) { options.forEach(option => { const key = option.name; this.categories[k ...

Avoid the sudden change in page content when using Router.Navigate

When the link below is clicked, the current page jumps to the top before proceeding to the next page. <a href="javascript:void(0);" (click)="goToTicket(x.refNo, $event)">{{x.ticketTitle}}</a> component.ts goToTicket(refNo, e) { e.prev ...