How to combine object properties in typescript?

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); 

(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

Tags:

Typescript