Remove fields from typescript interface object

Viewed 15371

I am getting a json response and storing it in mongodb, however the fields that I don't need are also getting in to the database, is there anyway to strip the uneseccary fields?

interface Test{
    name:string
};
const temp :Test = JSON.parse('{ "name":"someName","age":20 }') as Test;
console.log(temp);

output :

{ name: 'someName', age: 20 }
4 Answers

If you want to do this in a strongly-typed way, you can define a dummy/ideal object which satisfies your interface (const dummy: IMyInterface = {someField: "someVal"};), and then filter incoming objects' fields against Object.keys(dummy). This way your compiler will complain if you update the interface without updating this 'filtering' code.

Let say you have this object.

const x = {a: 1, b: 2, c: 3};

If you want to make a object with only a and b, you can use the following method.

const {c, ...y} = x;
console.log(y);

You will see that y has only a and b now.
Also this will not give an error if the field c was not in x. As an example,

const x: any = {a: 1, b: 2, c: 3};
const {d, ...y} = x;
console.log(y);

This works perfectly fine without any error and if you log the value of d, it will be undefined.

Related