Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Note: please restart the page if syntax highlighting works bad.
- interface MyObject {
- id: number;
- name: string | null;
- age?: number | null;
- address?: string | null;
- }
- const myObj: MyObject = { id: 1, name: null, age: 30 };
- function assignDefaults(a:MyObject, d:object)
- {
- var r = a as MyObject;
- for (const k in d) {
- a[k] = a[k] ?? d[k];
- }
- return r;
- }
- // 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' }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement