簡體   English   中英

過濾Typescript中的現有對象屬性

[英]Filter existing object properties in Typescript

我有一個any的打字稿對象,我需要的形狀,它是有效的給定接口。

我需要一種方法來創建新對象,以清除不屬於類定義的屬性,並添加缺少的屬性。

代碼示例可能是:

interface ImyInterface {
  a: string;
  b: string;
  c?:string;
};

let myObject = {
  a: "myString",
  d: "other value"
};

我的問題是:有沒有辦法轉換/過濾myObject ,使其適合接口ImyInterface定義,並轉換為

console.log (JSON.stringify(objectA));
> {a: 'myString', b: null}

也許有更好的方法,但是最有效的方法是:

    let otherObject: ImyInterface = { a: null, b: null };
    let x: ImyInterface = { ...otherObject, ...myObject };

第一行定義所需接口的對象。

第二行定義了所需接口的新對象,並將otherObject所有屬性復制到該對象中,然后將myObject中符合該接口的所有屬性復制到該對象中。

注意:如果您嘗試使用此:

let x: ImyInterface = { ...myObject };

您將看到一個錯誤,指出缺少接口的某些屬性。 因此,首先創建“完整”對象的原因(在我的示例中為otherObject )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM