小编典典

从打字稿接口对象中删除字段

json

我正在获取一个json响应并将其存储在mongodb中,但是我不需要的字段也正在进入数据库中,是否仍要剥离unseccary字段?

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

输出:

{ name: 'someName', age: 20 }

阅读 307

收藏
2020-07-27

共1个答案

小编典典

您可以使用从给定对象中选取某些属性的函数:

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;
}

然后:

let obj = { "name": "someName", "age": 20 };
let copy = pick(obj, "name") as Test;
console.log(copy); // { name: "someName" }
2020-07-27