Dev Helpers
← Back

Fill a missing field immutably

Fill a missing field immutably using TypeScript.

Open this example in the interactive library

Source code

type Profile = {
  name: string;
  contact?: { email?: string };
  score: number | null;
};
const profiles: Profile[] = [
  { name: "Ada", score: 0 },
  { name: "Ben", contact: { email: "b@example.org" }, score: null },
];
console.log(profiles.map((p) => ({ ...p, score: p.score ?? 1 })));

Sample output

[
  { name: 'Ada', score: 0 },
  { name: 'Ben', contact: { email: 'b@example.org' }, score: 1 }
]