How to combine object properties in typescript?












23














I'd like to know the best way to do this, say I have two objects



var objectA = {
propertyA: 1,
propertyB: 2
...
propertyM: 13
}

var objectB = {
propertyN: 14,
propertyO: 15
...
propertyZ: 26
}


If objectC is created by



var objectC = Object.assign(objectA, objectB);


How can I declare/describe objectC, so the compiler/IDE knows that it has the properties of both objectA and objectB?



I'd like to find a way without the need of defining interfaces for objectA and objectB. I don't want to write declaration and definition/evaluation for the same property twice. This redundancy is significant if I have too many properties on an object.



(Is there an operator that can extract the interface/type of an existing object?)



Is it possible?










share|improve this question



























    23














    I'd like to know the best way to do this, say I have two objects



    var objectA = {
    propertyA: 1,
    propertyB: 2
    ...
    propertyM: 13
    }

    var objectB = {
    propertyN: 14,
    propertyO: 15
    ...
    propertyZ: 26
    }


    If objectC is created by



    var objectC = Object.assign(objectA, objectB);


    How can I declare/describe objectC, so the compiler/IDE knows that it has the properties of both objectA and objectB?



    I'd like to find a way without the need of defining interfaces for objectA and objectB. I don't want to write declaration and definition/evaluation for the same property twice. This redundancy is significant if I have too many properties on an object.



    (Is there an operator that can extract the interface/type of an existing object?)



    Is it possible?










    share|improve this question

























      23












      23








      23


      2





      I'd like to know the best way to do this, say I have two objects



      var objectA = {
      propertyA: 1,
      propertyB: 2
      ...
      propertyM: 13
      }

      var objectB = {
      propertyN: 14,
      propertyO: 15
      ...
      propertyZ: 26
      }


      If objectC is created by



      var objectC = Object.assign(objectA, objectB);


      How can I declare/describe objectC, so the compiler/IDE knows that it has the properties of both objectA and objectB?



      I'd like to find a way without the need of defining interfaces for objectA and objectB. I don't want to write declaration and definition/evaluation for the same property twice. This redundancy is significant if I have too many properties on an object.



      (Is there an operator that can extract the interface/type of an existing object?)



      Is it possible?










      share|improve this question













      I'd like to know the best way to do this, say I have two objects



      var objectA = {
      propertyA: 1,
      propertyB: 2
      ...
      propertyM: 13
      }

      var objectB = {
      propertyN: 14,
      propertyO: 15
      ...
      propertyZ: 26
      }


      If objectC is created by



      var objectC = Object.assign(objectA, objectB);


      How can I declare/describe objectC, so the compiler/IDE knows that it has the properties of both objectA and objectB?



      I'd like to find a way without the need of defining interfaces for objectA and objectB. I don't want to write declaration and definition/evaluation for the same property twice. This redundancy is significant if I have too many properties on an object.



      (Is there an operator that can extract the interface/type of an existing object?)



      Is it possible?







      typescript






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked May 5 '16 at 4:51









      WawaBrother

      5881513




      5881513
























          4 Answers
          4






          active

          oldest

          votes


















          26














          Seems like this should do the trick:



          var objectA = {
          propertyA: 1,
          propertyB: 2,
          .
          . // more properties here
          .
          propertyM: 13
          };

          var objectB = {
          propertyN: 14,
          propertyO: 15,
          .
          . // more properties here
          .
          propertyZ: 26
          };

          var objectC = {...objectA, ...objectB}; // this is the answer

          var a = objectC.propertyA;

          var n = objectC.propertyN;


          Based on this article: https://blog.mariusschulz.com/2016/12/23/typescript-2-1-object-rest-and-spread





          In addition, the order of the variables in the decomposition matters.
          Consider the following:



          var objectA = {
          propertyA: 1,
          propertyB: 2, // same property exists in objectB
          propertyC: 3
          };

          var objectB = {
          propertyX: 'a',
          propertyB: 'b', // same property exists in objectA
          propertyZ: 'c'
          };

          // objectB will override existing properties, with the same name,
          // from the decomposition of objectA
          var objectC = {...objectA, ...objectB};

          // result: 'b'
          console.log(objectC.propertyB);

          // objectA will override existing properties, with the same name,
          // from the decomposition of objectB
          var objectD = {...objectB, ...objectA};

          // result: '2'
          console.log(objectD.propertyB);





          share|improve this answer























          • just to improve the answer: this line does the trick: var objectC = {...objectA, ...objectB};
            – Amirreza
            Aug 29 at 6:54



















          7















          so the compiler/IDE knows that it has the properties of both objectA and objectB?




          Use an intersection type + generics. E.g. from here



          /**
          * Quick and dirty shallow extend
          */
          export function extend<A>(a: A): A;
          export function extend<A, B>(a: A, b: B): A & B;
          export function extend<A, B, C>(a: A, b: B, c: C): A & B & C;
          export function extend<A, B, C, D>(a: A, b: B, c: C, d: D): A & B & C & D;
          export function extend(...args: any): any {
          const newObj = {};
          for (const obj of args) {
          for (const key in obj) {
          //copy all the fields
          newObj[key] = obj[key];
          }
          }
          return newObj;
          };


          More



          Both are mentioned here : https://basarat.gitbooks.io/typescript/content/docs/types/type-system.html






          share|improve this answer





















          • Thanks. This seems to work. However the extend() function is defined in a 3rd party library, is there any way to overwrite this specific definition for extend() in its d.ts file? (I am using underscore _.extend() ).
            – WawaBrother
            May 5 '16 at 7:50










          • Yup. Just modify underscore.d.ts
            – basarat
            May 5 '16 at 23:35



















          3














          Use Typescript spread operator it transpile to Javascript Object.assign()



          If you need deep tree object merging you could use changing function of best-global package






          share|improve this answer































            1















            (Is there an operator that can extract the interface/type of an
            existing object? Is it possible?)




            You should go for typeof.



            type typeA = typeof objectA;
            type typeB = typeof objectB;


            To get them merged you can use intersection operation as basarat already pointed out.



            type typeC = typeA & typeB





            share|improve this answer





















              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f37042602%2fhow-to-combine-object-properties-in-typescript%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              26














              Seems like this should do the trick:



              var objectA = {
              propertyA: 1,
              propertyB: 2,
              .
              . // more properties here
              .
              propertyM: 13
              };

              var objectB = {
              propertyN: 14,
              propertyO: 15,
              .
              . // more properties here
              .
              propertyZ: 26
              };

              var objectC = {...objectA, ...objectB}; // this is the answer

              var a = objectC.propertyA;

              var n = objectC.propertyN;


              Based on this article: https://blog.mariusschulz.com/2016/12/23/typescript-2-1-object-rest-and-spread





              In addition, the order of the variables in the decomposition matters.
              Consider the following:



              var objectA = {
              propertyA: 1,
              propertyB: 2, // same property exists in objectB
              propertyC: 3
              };

              var objectB = {
              propertyX: 'a',
              propertyB: 'b', // same property exists in objectA
              propertyZ: 'c'
              };

              // objectB will override existing properties, with the same name,
              // from the decomposition of objectA
              var objectC = {...objectA, ...objectB};

              // result: 'b'
              console.log(objectC.propertyB);

              // objectA will override existing properties, with the same name,
              // from the decomposition of objectB
              var objectD = {...objectB, ...objectA};

              // result: '2'
              console.log(objectD.propertyB);





              share|improve this answer























              • just to improve the answer: this line does the trick: var objectC = {...objectA, ...objectB};
                – Amirreza
                Aug 29 at 6:54
















              26














              Seems like this should do the trick:



              var objectA = {
              propertyA: 1,
              propertyB: 2,
              .
              . // more properties here
              .
              propertyM: 13
              };

              var objectB = {
              propertyN: 14,
              propertyO: 15,
              .
              . // more properties here
              .
              propertyZ: 26
              };

              var objectC = {...objectA, ...objectB}; // this is the answer

              var a = objectC.propertyA;

              var n = objectC.propertyN;


              Based on this article: https://blog.mariusschulz.com/2016/12/23/typescript-2-1-object-rest-and-spread





              In addition, the order of the variables in the decomposition matters.
              Consider the following:



              var objectA = {
              propertyA: 1,
              propertyB: 2, // same property exists in objectB
              propertyC: 3
              };

              var objectB = {
              propertyX: 'a',
              propertyB: 'b', // same property exists in objectA
              propertyZ: 'c'
              };

              // objectB will override existing properties, with the same name,
              // from the decomposition of objectA
              var objectC = {...objectA, ...objectB};

              // result: 'b'
              console.log(objectC.propertyB);

              // objectA will override existing properties, with the same name,
              // from the decomposition of objectB
              var objectD = {...objectB, ...objectA};

              // result: '2'
              console.log(objectD.propertyB);





              share|improve this answer























              • just to improve the answer: this line does the trick: var objectC = {...objectA, ...objectB};
                – Amirreza
                Aug 29 at 6:54














              26












              26








              26






              Seems like this should do the trick:



              var objectA = {
              propertyA: 1,
              propertyB: 2,
              .
              . // more properties here
              .
              propertyM: 13
              };

              var objectB = {
              propertyN: 14,
              propertyO: 15,
              .
              . // more properties here
              .
              propertyZ: 26
              };

              var objectC = {...objectA, ...objectB}; // this is the answer

              var a = objectC.propertyA;

              var n = objectC.propertyN;


              Based on this article: https://blog.mariusschulz.com/2016/12/23/typescript-2-1-object-rest-and-spread





              In addition, the order of the variables in the decomposition matters.
              Consider the following:



              var objectA = {
              propertyA: 1,
              propertyB: 2, // same property exists in objectB
              propertyC: 3
              };

              var objectB = {
              propertyX: 'a',
              propertyB: 'b', // same property exists in objectA
              propertyZ: 'c'
              };

              // objectB will override existing properties, with the same name,
              // from the decomposition of objectA
              var objectC = {...objectA, ...objectB};

              // result: 'b'
              console.log(objectC.propertyB);

              // objectA will override existing properties, with the same name,
              // from the decomposition of objectB
              var objectD = {...objectB, ...objectA};

              // result: '2'
              console.log(objectD.propertyB);





              share|improve this answer














              Seems like this should do the trick:



              var objectA = {
              propertyA: 1,
              propertyB: 2,
              .
              . // more properties here
              .
              propertyM: 13
              };

              var objectB = {
              propertyN: 14,
              propertyO: 15,
              .
              . // more properties here
              .
              propertyZ: 26
              };

              var objectC = {...objectA, ...objectB}; // this is the answer

              var a = objectC.propertyA;

              var n = objectC.propertyN;


              Based on this article: https://blog.mariusschulz.com/2016/12/23/typescript-2-1-object-rest-and-spread





              In addition, the order of the variables in the decomposition matters.
              Consider the following:



              var objectA = {
              propertyA: 1,
              propertyB: 2, // same property exists in objectB
              propertyC: 3
              };

              var objectB = {
              propertyX: 'a',
              propertyB: 'b', // same property exists in objectA
              propertyZ: 'c'
              };

              // objectB will override existing properties, with the same name,
              // from the decomposition of objectA
              var objectC = {...objectA, ...objectB};

              // result: 'b'
              console.log(objectC.propertyB);

              // objectA will override existing properties, with the same name,
              // from the decomposition of objectB
              var objectD = {...objectB, ...objectA};

              // result: '2'
              console.log(objectD.propertyB);






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Nov 22 at 20:55

























              answered Nov 27 '17 at 18:45









              Alkasai

              777620




              777620












              • just to improve the answer: this line does the trick: var objectC = {...objectA, ...objectB};
                – Amirreza
                Aug 29 at 6:54


















              • just to improve the answer: this line does the trick: var objectC = {...objectA, ...objectB};
                – Amirreza
                Aug 29 at 6:54
















              just to improve the answer: this line does the trick: var objectC = {...objectA, ...objectB};
              – Amirreza
              Aug 29 at 6:54




              just to improve the answer: this line does the trick: var objectC = {...objectA, ...objectB};
              – Amirreza
              Aug 29 at 6:54













              7















              so the compiler/IDE knows that it has the properties of both objectA and objectB?




              Use an intersection type + generics. E.g. from here



              /**
              * Quick and dirty shallow extend
              */
              export function extend<A>(a: A): A;
              export function extend<A, B>(a: A, b: B): A & B;
              export function extend<A, B, C>(a: A, b: B, c: C): A & B & C;
              export function extend<A, B, C, D>(a: A, b: B, c: C, d: D): A & B & C & D;
              export function extend(...args: any): any {
              const newObj = {};
              for (const obj of args) {
              for (const key in obj) {
              //copy all the fields
              newObj[key] = obj[key];
              }
              }
              return newObj;
              };


              More



              Both are mentioned here : https://basarat.gitbooks.io/typescript/content/docs/types/type-system.html






              share|improve this answer





















              • Thanks. This seems to work. However the extend() function is defined in a 3rd party library, is there any way to overwrite this specific definition for extend() in its d.ts file? (I am using underscore _.extend() ).
                – WawaBrother
                May 5 '16 at 7:50










              • Yup. Just modify underscore.d.ts
                – basarat
                May 5 '16 at 23:35
















              7















              so the compiler/IDE knows that it has the properties of both objectA and objectB?




              Use an intersection type + generics. E.g. from here



              /**
              * Quick and dirty shallow extend
              */
              export function extend<A>(a: A): A;
              export function extend<A, B>(a: A, b: B): A & B;
              export function extend<A, B, C>(a: A, b: B, c: C): A & B & C;
              export function extend<A, B, C, D>(a: A, b: B, c: C, d: D): A & B & C & D;
              export function extend(...args: any): any {
              const newObj = {};
              for (const obj of args) {
              for (const key in obj) {
              //copy all the fields
              newObj[key] = obj[key];
              }
              }
              return newObj;
              };


              More



              Both are mentioned here : https://basarat.gitbooks.io/typescript/content/docs/types/type-system.html






              share|improve this answer





















              • Thanks. This seems to work. However the extend() function is defined in a 3rd party library, is there any way to overwrite this specific definition for extend() in its d.ts file? (I am using underscore _.extend() ).
                – WawaBrother
                May 5 '16 at 7:50










              • Yup. Just modify underscore.d.ts
                – basarat
                May 5 '16 at 23:35














              7












              7








              7







              so the compiler/IDE knows that it has the properties of both objectA and objectB?




              Use an intersection type + generics. E.g. from here



              /**
              * Quick and dirty shallow extend
              */
              export function extend<A>(a: A): A;
              export function extend<A, B>(a: A, b: B): A & B;
              export function extend<A, B, C>(a: A, b: B, c: C): A & B & C;
              export function extend<A, B, C, D>(a: A, b: B, c: C, d: D): A & B & C & D;
              export function extend(...args: any): any {
              const newObj = {};
              for (const obj of args) {
              for (const key in obj) {
              //copy all the fields
              newObj[key] = obj[key];
              }
              }
              return newObj;
              };


              More



              Both are mentioned here : https://basarat.gitbooks.io/typescript/content/docs/types/type-system.html






              share|improve this answer













              so the compiler/IDE knows that it has the properties of both objectA and objectB?




              Use an intersection type + generics. E.g. from here



              /**
              * Quick and dirty shallow extend
              */
              export function extend<A>(a: A): A;
              export function extend<A, B>(a: A, b: B): A & B;
              export function extend<A, B, C>(a: A, b: B, c: C): A & B & C;
              export function extend<A, B, C, D>(a: A, b: B, c: C, d: D): A & B & C & D;
              export function extend(...args: any): any {
              const newObj = {};
              for (const obj of args) {
              for (const key in obj) {
              //copy all the fields
              newObj[key] = obj[key];
              }
              }
              return newObj;
              };


              More



              Both are mentioned here : https://basarat.gitbooks.io/typescript/content/docs/types/type-system.html







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered May 5 '16 at 5:11









              basarat

              134k23247353




              134k23247353












              • Thanks. This seems to work. However the extend() function is defined in a 3rd party library, is there any way to overwrite this specific definition for extend() in its d.ts file? (I am using underscore _.extend() ).
                – WawaBrother
                May 5 '16 at 7:50










              • Yup. Just modify underscore.d.ts
                – basarat
                May 5 '16 at 23:35


















              • Thanks. This seems to work. However the extend() function is defined in a 3rd party library, is there any way to overwrite this specific definition for extend() in its d.ts file? (I am using underscore _.extend() ).
                – WawaBrother
                May 5 '16 at 7:50










              • Yup. Just modify underscore.d.ts
                – basarat
                May 5 '16 at 23:35
















              Thanks. This seems to work. However the extend() function is defined in a 3rd party library, is there any way to overwrite this specific definition for extend() in its d.ts file? (I am using underscore _.extend() ).
              – WawaBrother
              May 5 '16 at 7:50




              Thanks. This seems to work. However the extend() function is defined in a 3rd party library, is there any way to overwrite this specific definition for extend() in its d.ts file? (I am using underscore _.extend() ).
              – WawaBrother
              May 5 '16 at 7:50












              Yup. Just modify underscore.d.ts
              – basarat
              May 5 '16 at 23:35




              Yup. Just modify underscore.d.ts
              – basarat
              May 5 '16 at 23:35











              3














              Use Typescript spread operator it transpile to Javascript Object.assign()



              If you need deep tree object merging you could use changing function of best-global package






              share|improve this answer




























                3














                Use Typescript spread operator it transpile to Javascript Object.assign()



                If you need deep tree object merging you could use changing function of best-global package






                share|improve this answer


























                  3












                  3








                  3






                  Use Typescript spread operator it transpile to Javascript Object.assign()



                  If you need deep tree object merging you could use changing function of best-global package






                  share|improve this answer














                  Use Typescript spread operator it transpile to Javascript Object.assign()



                  If you need deep tree object merging you could use changing function of best-global package







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 9 at 16:46

























                  answered Mar 9 at 16:09









                  Eugenio

                  30727




                  30727























                      1















                      (Is there an operator that can extract the interface/type of an
                      existing object? Is it possible?)




                      You should go for typeof.



                      type typeA = typeof objectA;
                      type typeB = typeof objectB;


                      To get them merged you can use intersection operation as basarat already pointed out.



                      type typeC = typeA & typeB





                      share|improve this answer


























                        1















                        (Is there an operator that can extract the interface/type of an
                        existing object? Is it possible?)




                        You should go for typeof.



                        type typeA = typeof objectA;
                        type typeB = typeof objectB;


                        To get them merged you can use intersection operation as basarat already pointed out.



                        type typeC = typeA & typeB





                        share|improve this answer
























                          1












                          1








                          1







                          (Is there an operator that can extract the interface/type of an
                          existing object? Is it possible?)




                          You should go for typeof.



                          type typeA = typeof objectA;
                          type typeB = typeof objectB;


                          To get them merged you can use intersection operation as basarat already pointed out.



                          type typeC = typeA & typeB





                          share|improve this answer













                          (Is there an operator that can extract the interface/type of an
                          existing object? Is it possible?)




                          You should go for typeof.



                          type typeA = typeof objectA;
                          type typeB = typeof objectB;


                          To get them merged you can use intersection operation as basarat already pointed out.



                          type typeC = typeA & typeB






                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered Dec 10 '17 at 23:23









                          Hav

                          352211




                          352211






























                              draft saved

                              draft discarded




















































                              Thanks for contributing an answer to Stack Overflow!


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.





                              Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                              Please pay close attention to the following guidance:


                              • Please be sure to answer the question. Provide details and share your research!

                              But avoid



                              • Asking for help, clarification, or responding to other answers.

                              • Making statements based on opinion; back them up with references or personal experience.


                              To learn more, see our tips on writing great answers.




                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f37042602%2fhow-to-combine-object-properties-in-typescript%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              What visual should I use to simply compare current year value vs last year in Power BI desktop

                              Alexandru Averescu

                              Trompette piccolo