简体   繁体   中英

How to create a TypeScript object with only selected properties?

I have a TypeScript object that looks like this:

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

How can I create an object of type User, with only the fields I want it to have?

For example, I want to be able to create a User object that only contains id and displayName , but without the location and otherAttribute properties. 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. Is there a way to get around this?

From my understanding all you need is to create an instance of type User , with only certain properties.

You can do it in several ways. The most straightforward way is to make use of either the Pick or Omit utilities from TypeScript, like so:

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

[EDIT] I didn't fully grasp your requirement. But if you want to just make some of the properties partial and keep the rest of properties from User intact, then make use of the Optional utility, like so:

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

Then you can setup your class like this, with all properties Partial by default:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM