TypeScript – Add/Modify/Delete RecordType

The Record<Keys,Type>utility type in TypeScript is a powerful dictionary like utility.

Assume you want to track employees by employee id and their relevant employee details.

Creating

interface PersonInfo {
  firstName: string;
  lastName: string;
  position: string
}

type EmployeeId = number;

const employees: Record<EmployeeId, PersonInfo> = {
  412: { firstName: 'Jon', lastName: 'Williams', position: 'Developer' },
  89: { firstName: 'Mary', lastName: 'Anderson', position: 'Manager' }
};

// Current employess
console.log(employees);

The output from console.log:


{
  "412": {
    "firstName": "Jon",
    "lastName": "Williams",
    "position": "Developer"
  },
  "89": {
    "firstName": "Mary",
    "lastName": "Anderson",
    "position": "Manager"
  }
} 

Adding

interface PersonInfo {
  firstName: string;
  lastName: string;
  position: string
}

type EmployeeId = number;

const employees: Record<EmployeeId, PersonInfo> = {
  412: { firstName: 'Jon', lastName: 'Williams', position: 'Developer' },
  89: { firstName: 'Mary', lastName: 'Anderson', position: 'Manager' }
};

// New employee added
employees[345] = { firstName: 'Phil', lastName: 'Ford', position: 'Developer'};
console.log(employees);

The output from console.log:

{
  "89": {
    "firstName": "Mary",
    "lastName": "Anderson",
    "position": "Manager"
  },
  "345": {
    "firstName": "Phil",
    "lastName": "Ford",
    "position": "Developer"
  },
  "412": {
    "firstName": "Jon",
    "lastName": "Williams",
    "position": "Developer"
  }
} 

Modifying

interface PersonInfo {
  firstName: string;
  lastName: string;
  position: string
}

type EmployeeId = number;

const employees: Record<EmployeeId, PersonInfo> = {
  412: { firstName: 'Jon', lastName: 'Williams', position: 'Developer' },
  89: { firstName: 'Mary', lastName: 'Anderson', position: 'Manager' }
};

// Modifying employee
employees[412] = { firstName: 'Phil', lastName: 'Ford', position: 'Developer'};
console.log(employees);

The output from console.log:

{
  "89": {
    "firstName": "Mary",
    "lastName": "Anderson",
    "position": "Manager"
  },
  "412": {
    "firstName": "Phil",
    "lastName": "Ford",
    "position": "Developer"
  }
} 

Deleting

interface PersonInfo {
  firstName: string;
  lastName: string;
  position: string
}

type EmployeeId = number;

const employees: Record<EmployeeId, PersonInfo> = {
  412: { firstName: 'Jon', lastName: 'Williams', position: 'Developer' },
  89: { firstName: 'Mary', lastName: 'Anderson', position: 'Manager' }
};

// Deleting employee
delete employees[412];
console.log(employees);

The output from console.log:

{
  "89": {
    "firstName": "Mary",
    "lastName": "Anderson",
    "position": "Manager"
  }
} 

Dan