Issue
I want to change null
to another value in an object, eg:
interface MyObject {
id: number;
name: string | null;
age?: number | null;
address?: string | null;
}
const myObj: MyObject = { id: 1, name: null, age: 30 };
// assignDefaults is my function
const newMyObj = assignDefaults(myObj, {
name: 'Default Name',
address: 'New York',
});
console.log(newMyObj); // desired output:{ id: 1, name: 'Default Name', age: 30, address: 'New York' }
How to realize function assignDefaults
?
Note: Only set value when null.
Solution
Just iterate over the properties of your default object and juse the ??=
operator to assign the values to the original object. Using foo.xy ??= bar.xy
will only do the assignment, if foo.xy
is "nullish" (ie null
or undefined
). Thus it will not replace existing properties.
The //@ts-ignore
here is necessary, because TS is not (yet?) capable ensuring the correctness when using keyof
on a generic type (what for .. in
loop implicitly does). But it's still safe here, because, Partial<T>
cannot have any keys that don't exist in T
.
interface MyObject {
id: number;
name: string | null;
age?: number | null;
address?: string | null;
}
const myObj: MyObject = { id: 1, name: null, age: 30 };
const def: Partial<MyObject> = { name: "foo", address: "bar", age: 0 }
function assignDefaults<T>(obj: T, def: Partial<T>): T {
//create a new result object to avoid manipulating the existing object
//if you want to amend in place you can skip this
let res = {...obj}
for (let k in def) { //iterate over all properties in the default object
//@ts-ignore
res[k] ??= def[k]; //assign the default value only if the orignal property is null or undefined
}
return res;
}
let obj = assignDefaults(myObj, def);
console.log(obj);
Running the above example for instance in TS Playground will show you that it repalces the name: null
from the original object, but keeps the age: 30
Answered By - derpirscher
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.