Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove fields from typescript interface object

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 }
like image 803
Bekzod Avatar asked May 26 '17 13:05

Bekzod


People also ask

How do I remove a field from an object in TypeScript?

To remove a property from an object in TypeScript, mark the property as optional on the type and use the delete operator. You can only remove properties that have been marked optional from an object.

How do I use omit TypeScript?

The TypeScript Omit utility type It will remove the fields you defined. We want to remove the id field from our user object when we want to create a user. type UserPost = Omit<User, 'id'>; const updateUser: UserPost = { firstname: 'Chris', lastname: 'Bongers', age: 32, };

Can TypeScript interface have methods?

A TypeScript Interface can include method declarations using arrow functions or normal functions, it can also include properties and return types. The methods can have parameters or remain parameterless.

How do you remove a property from an array?

To remove a property from all objects in an array:Use the Array. forEach() method to iterate over the array. On each iteration, use the delete operator to delete the specific property. The property will get removed from all objects in the array.


1 Answers

You can use a function that picks certain properties from a given object:

function pick<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K> {
    const copy = {} as Pick<T, K>;

    keys.forEach(key => copy[key] = obj[key]);

    return copy;
}

Then:

let obj = { "name": "someName", "age": 20 };
let copy = pick(obj, "name") as Test;
console.log(copy); // { name: "someName" }
like image 92
Nitzan Tomer Avatar answered Sep 21 '22 12:09

Nitzan Tomer