Reputation: 96
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.
Upvotes: 0
Views: 345
Reputation: 96
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.
Upvotes: 1