Advertisement
manger32

Stackoverflow question, sample interfaces in Typescript

Feb 1st, 2024
654
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
TypeScript 0.61 KB | Source Code | 0 0
  1. // Note: please restart the page if syntax highlighting works bad.
  2. interface MyObject {
  3.   id: number;
  4.   name: string | null;
  5.   age?: number | null;
  6.   address?: string | null;
  7. }
  8.  
  9. const myObj: MyObject = { id: 1, name: null, age: 30 };
  10. function assignDefaults(a:MyObject, d:object)
  11. {
  12.   var r = a as MyObject;
  13.   for (const k in d) {
  14.       a[k] = a[k] ?? d[k];
  15.   }
  16.   return r;
  17. }
  18. // assignDefaults is my function
  19. const newMyObj = assignDefaults(myObj, {
  20.   name: 'Default Name',
  21.   address: 'New York',
  22. });
  23.  
  24. 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