Search code examples
classooptypescriptobjectnew-operator

Unable to create typescript class object


New to typescript, I came across Typescript class like the following.

export class Errors {
    errors: { [key: string]: string } = {};
}

I am trying to create this error object manually. Can you show usage of this? i tried the following.

errList: Errors = new Errors();

errList = {'key':'value'};

errList = [
      {
        Key: "code1",
        value: "err1"
      },
      {
        Key: "code2",
        value: "err2"
      },
    ]

errList.errors = {
    [key1]:"myValueX" , [key3]:"myValueY"
};

Solution

  • To initialize the class as you declared it you would have to use :

    var err = new Errors();
    err.errors = {
        "key": "value"
    };
    

    Another alternative would be to also define a constructor then you could initialize like this:

    export class Errors {
        constructor(public errors: { [key: string]: string } = {}){};
    }
    
    var err = new Errors({
        "key": "value"
    });
    

    If you do not have any errors on the class you could also use an interface instead and then you wouldn't need a constructor and you could just use object literals to initialize:

    export interface  Errors {
        errors: { [key: string]: string };
    }
    
    var err: Errors = {
        errors: {  "key": "value" }
    };
    

    Which one you choose is a matter of preference and your use case. I would go for the constructor version, as is the most concise to initialize but also lets you use the instanceof operator, which the interface version does not.