1

Working in Angular/TypeScript, a small question: Say I have a defined object with nested objects, and a blank constructor. (And in this case, it's from a package so I cannot edit it; otherwise I'd add a constructor.)

Currently I initialize it like this:

var childObj = new ChildObj();
childObj.ChildProp = 'my child prop';

var myObj = new MyObj();
myObj.Prop1 = 'foo';
myObj.Prop2 = 'bar';
myObj.ChildProp = childObj;

Is there a less cumbersome way of achieving the above? I don't think object initialization syntax works in JS/TypeScript. I'd love to use that kind of syntax:

var myObj = new MyObj {
    Prop1 = 'foo',
    Prop2 = 'bar',
    ChildObj = new ChildObj {
        childObj.ChildProp = 'my child prop'
    }
};

2 Answers 2

2

Try this:

let myObj = {
    prop1: 'foo',
    pop2: 'bar',
    childObj: {
        childProp: 'my child prop'
    }
} as MyObj;
Sign up to request clarification or add additional context in comments.

Comments

0

You can use spreading:

var myObj =  { ...(new MyObj()), Prop1: "foo", Prop2: "bar", ChildObj: { ...(new ChidlObj()), ChildProp: "my child prop" } };

1 Comment

Note that this will break the prototype chain, so the methods might be missing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.