5

For example, in c#, we have this snippet:

 class OrderLine
    {
        public OrderLine(){
          OrderId ="1",
          ItemTitle ="2"
        Console.WriteLine("constructing");
        }
        public string Platform { get; set; }
        public string OrderId { get; set; }
        public string ItemTitle { get; set; }
    }

    public static void Main()
    {
        var ol = new OrderLine 
        {
                Platform ="p"
        };
        Console.WriteLine(ol.Platform); 
    }

In Typescript, if I use {} to initialize an object, I won't be able to call the constrcuor which can give me some default value and do something else. if I use new key word to do some default construction, my compiler doesn't allow me to use object initializer(I am using angular 6), and I have to call ol.Platform to assign property value. When I have several properties to set value, writing multiple "ol." is not as fast as to use the object initializer syntax. is there a better way?

2 Answers 2

3

You can have the constructor accept an object for which each of its properties get assigned to the instance with Object.assign:

type Init = {
    age: number;
    gender: string;
};
class Foo {
    public name: string;
    public age: number | undefined;
    public gender: string | undefined;
    constructor(name: string, init?: Partial<Init>) {
        this.name = name;
        if (init) {
          Object.assign(this, init);
        }
    }
}
const f = new Foo('bob', { age: 10 });
Sign up to request clarification or add additional context in comments.

2 Comments

it's tricky, but for my large model with dozens of property, this works. But I prefer not to define a Partial Init type, can I use any here?
You can always use any to get around having to do type-checking, but it's usually not a good idea, because then you might as well not be using Typescript at all for that point in the code. If you use any, then the keys and values of the new instance could be literally anything, and you lose all of the type safety Typescript was made to help you with.
0

Adding this to the original answer ...

You can define init as the same type, i.e. Partial<Foo>

@RoutingKey('abc')
class Foo {
    public name: string | undefined;
    public age: number | undefined;
    public gender: string | undefined;
    constructor(init?: Partial<Foo>) {
        if (init) {
            Object.assign(this, init);
        }
    }
}

const foo = new Foo({ name: 'something' });

This was useful to me as I had to call new to get the constructor decorator @RoutingKey() to fire

Comments

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.