CyrefJS
CCyrefJS
فا
Back to documentation
Object/Since 1.38.0

set

Creates a shallow copy of an object with the specified property replaced by a new value.

set(object, key, value):T

How it works

The function first creates a shallow copy using object spread syntax, then assigns the provided value to the specified key on that copy.

Type safety

The key is constrained to keyof T and the value uses T[K]. This means TypeScript connects the selected key with its corresponding property type.

Shallow copy

Only the top-level object is copied. Nested objects and arrays retain their original references.

Original object

The input object is not directly modified. The assignment is performed on the newly created copy.

Parameters

objectTrequired

The object to copy and update.

keyKrequired

The key of the property to update.

valueT[K]required

The new value for the specified property. Its type must match the property's type.

Returns

T

A new shallow copy of the object with the specified property set to the provided value.

Examples

01

Basic usage

TypeScript
const user = {
  name: "Amir",
  age: 22,
};

const result = set(user, "age", 25);

// {
//   name: "Amir",
//   age: 25,
// }
02

Update a string property

TypeScript
const user = {
  name: "Amir",
  age: 22,
};

set(user, "name", "Ali");
// {
//   name: "Ali",
//   age: 22,
// }
03

Update a boolean property

TypeScript
const settings = {
  darkMode: false,
  notifications: true,
};

set(settings, "darkMode", true);
// {
//   darkMode: true,
//   notifications: true,
// }
04

Type-safe values

TypeScript
const user = {
  name: "Amir",
  age: 22,
};

set(user, "age", 25);
// Valid

// set(user, "age", "25");
// TypeScript error
05

Original object is unchanged

TypeScript
const user = {
  name: "Amir",
  age: 22,
};

const result = set(user, "age", 25);

console.log(user);
// {
//   name: "Amir",
//   age: 22,
// }
06

Shallow copy

TypeScript
const user = {
  name: "Amir",
  profile: {
    age: 22,
  },
};

const result = set(user, "name", "Ali");

result.profile.age = 25;

console.log(user.profile.age);
// 25
07

Set a value to undefined

TypeScript
const data = {
  value: 10 as number | undefined,
};

set(data, "value", undefined);
// {
//   value: undefined,
// }
08

Set a value to null

TypeScript
const data = {
  value: 10 as number | null,
};

set(data, "value", null);
// {
//   value: null,
// }
Built with@cyref/js·Official documentation