Home > Software engineering >  Append elements to Record object in Typescript
Append elements to Record object in Typescript

Time:09-27

I have a method that itself defines a default Record<string,string> object, and takes in an argument of type Record<string,string>. The aim is to append the argument Record to the default Record.

export interface DataRecord {
  headers: Record<string,string>;
}

public appendToRecord(submittedRecord?: Record<string,string>) {
  let defaultRecord: DataRecord = {
    headers: {
      header1: 'a',
      header2: 'b',
      header3: 'c',
    }
  }
  if(submittedRecord) {
    defaultRecord.headers[submittedRecord.key] = submittedRecord.value;  // not working
  }
}

The expectation is that, if submittedRecord contains header4: 'd', I will be able to output defaultRecord.headers and get something like:

headers: {
  header1: 'a',
  header2: 'b',
  header3: 'c',
  header4: 'd'
}

With my current code, submittedRecord.key and submittedRecord.value is always undefined. I understand that Record may be different from how a typical key-value pair is treated, but I don't know of any other way I can append to an existing Record.

CodePudding user response:

How about this?

public appendToRecord(submittedRecord?: Record<string,string>) {
  const defaultRecord: DataRecord = {
    headers: {
      header1: 'a',
      header2: 'b',
      header3: 'c',
      ...submittedRecord,
    }
  };
  ...
}

Playground link

  • Related