20

I want to remove all properties from an object which are not declared in a specific type interface.

For example, let's assume that I have the following interface:

export interface CreateCustomerUserInput {
    fullname: string;
    email: string;
}

And I have the following object:

let obj = {fullname: 'AAA', email: 'aa@aa.com', phone: '111', address: 'XXX'};

But I want to create a new object with only properties declared in the type interface. Here is the expected object:

let c = {fullname: 'AAA', email: 'aa@aa.com'}

Is there any good way to solve this in TypeScript?

ggradnig
  • 13,119
  • 2
  • 37
  • 61
Patrick Blind
  • 399
  • 1
  • 4
  • 15

1 Answers1

8

If I understand you correctly, you want to strip away all properties from an object that are not defined in a specific type interface.

Unfortunately, type interfaces are not available at runtime - meaning, they don't exist when running the JavaScript code. Therefore, there is no way to access reflective information about the type programmatically.

However, you might be successful by using a class. For example, let's assume you have the following class:

export class CreateCustomerUserInput {
    public fullname: string = "";
    public email: string = "";
}

You could create an instance of that class and iterate over its properties using a for.. in loop or with Object.keys(). Then you could strip away the properties of your given object by using delete for each property that is not available in the instance of your class.

For this to work, make sure all properties of the class are initialized after construction.

Another way is using TypeScript decorators with the experimental metadata flag, as explained here: http://www.typescriptlang.org/docs/handbook/decorators.html.

They preserve reflective information, but only for classes (or abstract classes)!

ggradnig
  • 13,119
  • 2
  • 37
  • 61