1.38.0set
Creates a shallow copy of an object with the specified property replaced by a new value.
set(object, key, value):THow 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
objectTrequiredThe object to copy and update.
keyKrequiredThe key of the property to update.
valueT[K]requiredThe new value for the specified property. Its type must match the property's type.
Returns
TA new shallow copy of the object with the specified property set to the provided value.
Examples
Basic usage
const user = {
name: "Amir",
age: 22,
};
const result = set(user, "age", 25);
// {
// name: "Amir",
// age: 25,
// }Update a string property
const user = {
name: "Amir",
age: 22,
};
set(user, "name", "Ali");
// {
// name: "Ali",
// age: 22,
// }Update a boolean property
const settings = {
darkMode: false,
notifications: true,
};
set(settings, "darkMode", true);
// {
// darkMode: true,
// notifications: true,
// }Type-safe values
const user = {
name: "Amir",
age: 22,
};
set(user, "age", 25);
// Valid
// set(user, "age", "25");
// TypeScript errorOriginal object is unchanged
const user = {
name: "Amir",
age: 22,
};
const result = set(user, "age", 25);
console.log(user);
// {
// name: "Amir",
// age: 22,
// }Shallow copy
const user = {
name: "Amir",
profile: {
age: 22,
},
};
const result = set(user, "name", "Ali");
result.profile.age = 25;
console.log(user.profile.age);
// 25Set a value to undefined
const data = {
value: 10 as number | undefined,
};
set(data, "value", undefined);
// {
// value: undefined,
// }Set a value to null
const data = {
value: 10 as number | null,
};
set(data, "value", null);
// {
// value: null,
// }