0
interface IField { readonly name : string; readonly value : string; readonly inline ?: boolean; } class Field implements IField { readonly name : string; readonly value : string; readonly inline ?: boolean; constructor(data : IField) { this.name = data.name; this.value = data.value; this.inline = data.inline; } } 

When trying to initialize a new variable from the Field class inside another class like so,

class Embed implements IEmbed { ... constructor(data : IEmbed) { ... this.fields = data.fields.map((field) => new Field(field)); ... } } 

My program crashes with the error,

 this.name = data.name; ^ TypeError: Cannot read property 'name' of undefined 

If I log the value of data inside the constructor(...) method for Field, it prints out the object without any issue (changed values for privacy),

{ value: '...message...', name: '...name...', inline: false } 

But it still crashes. The value given to the Embed constructor is a parsed JSON object from a websocket, and thus the same is true for the Field constructor.

3
  • 2
    What's IEmbed ? Commented Sep 26, 2021 at 14:57
  • The interface for Embed, although I just pass the JSON data from the websocket to the constructor's data parameter for it. Commented Sep 26, 2021 at 15:13
  • 1
    We know it's an interface but it's definition is missing. As for the error, if a field is null, the copy constructor will fall like yours does. Commented Sep 26, 2021 at 15:25

1 Answer 1

1

Ended up using the solution from this question.

class Field implements IField { readonly name : string; readonly value : string; readonly inline ?: boolean; constructor(data : Partial<Field> = {}) { Object.assign(this, data); } } 

I replaced the data : any portion with data : Partial<Field> = {}, providing a default for the field. Thanks to Wiktor for steering me in the right direction.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.