簡體   English   中英

如何創建僅具有選定屬性的 TypeScript object?

[英]How to create a TypeScript object with only selected properties?

我有一個 TypeScript object 看起來像這樣:

class User {
  id: string = "";
  location: string = "";
  displayName: string = "";
  otherAttribute: string = "";
}

如何創建一個用戶類型的 object,只包含我想要的字段?

例如,我希望能夠創建一個僅包含iddisplayName但沒有locationotherAttribute屬性的用戶 object 。 I need to create a new object without unwanted properties to use DynamoDB DataMapper, which is an ORM library that interfaces with DynamoDB and uses the class properties to map to the DynamoDB table attributes dynamically. This was working fine before using plain JavaScript because I didn't declare any property in my JavaScript User class but now need to for TypeScript. 有沒有辦法解決這個問題?

據我了解,您只需要創建一個User類型的實例,它只有某些屬性。

您可以通過多種方式做到這一點。 最直接的方法是使用 TypeScript 中的PickOmit實用程序,如下所示:

const cherryPickedInstance: Pick<User, "id" | "displayName"> = {
  "id": "123",
  "displayName": "Oliver" 
};

// or make use of Omit
const omittedInstance: Omit<User, "otherAttribute" | "location"> = {
  "id": "1234",
  "displayName": "Sam" 
};

[編輯] 我沒有完全掌握你的要求。 但是,如果您只想使某些屬性成為部分屬性並保持來自User的屬性的 rest 完整,那么請使用Optional實用程序,如下所示:

type Optional<T, K extends keyof T> = Pick<Partial<T>, K> & Omit<T, K>;

然后你可以像這樣設置你的 class ,默認情況下所有屬性都是Partial

class User {
  id: string = "";
  location: string = "";
  displayName: string = "";
  otherAttribute: string = "";

    public constructor(
        fields?: {
          id?: string;
          location?: string;
          displayName?: string;
          otherAttribute?: string;
        }) {
        if (fields) Object.assign(this, fields);
    }
}

const optionalCLassInstnace: Optional<User, "location" | "otherAttribute"> = new User({
  "id": "1", 
  "displayName": "Optional"
});

暫無
暫無

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

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