Home > Enterprise >  Typescript: Copy Type List into another Type List with similar members
Typescript: Copy Type List into another Type List with similar members

Time:07-12

In Typescript, I want to take an ArrayList of ProcedureCode, and copy all the contents into ArrayList of ProcedureView. This will keep the similar members, while have null values temporarily for 2 new members in ProcedureView. Whats an easy way to do this? researching answers with spread operator , and following https://stackoverflow.com/a/57109024/15435022

export type ProcedureCode = {
  code: string;
  officialName: string;
  localName: string;
  active: boolean;
};

export type ProcedureView = ProcedureCode & {
  inventory: number;
  itemDescription: string;
};

CodePudding user response:

I am thinking about this implementations

export type ProcedureCode = {
  code: string;
  officialName: string;
  localName: string;
  active: boolean;
};

export type ProcedureView = ProcedureCode & {
  inventory: number | null;
  itemDescription: string | null;
};

const procedureCodes: ProcedureCode[] = [
  {
    code: "code",
    officialName: "official name",
    localName: "local name",
    active: false
  },
  {
    code: "code 2",
    officialName: "official name 2",
    localName: "local name 2",
    active: false
  }
];

const procedureViews: ProcedureView[] = procedureCodes.map((procedureCode) => {
  const procedureView = {
    ...procedureCode,
    inventory: null,
    itemDescription: null
  };

  return procedureView;
});
  • Related