1

I am writing a service but am encountering a problem.

The service contains a variable that is implementing an interface. When the service is first created the variable holds the value of undefined.

To explain it with less code I came up with the following example.

This is an interface.

interface objectWithSensors {
  sensor1: number[];
  sensor2: number[];
}

The service has a varaible of this type declared as:

private sensorObject: objectWithSensors;

At this point in time this object is undefined.

Is there a way to define it at this point (put an object in there that I can later modify) or should I change the interface to a class with public attributes?

3
  • You should initialize sensorObject with a value. You need to define a class that implements this interface. You then instantiate an object of this class, for example in your service's constrictor, or you use dependency injection to assign it. Commented Aug 28, 2019 at 13:00
  • That's how I was told to use interfaces in a conventional way as well. But from what I understand Angular uses them to make binding to properties more easy. Declaring a variable of that interface type makes it possible to do stuff like sensorObject.sensor1.push(1). In short the variable implements the interface and you do not need an entire class. Commented Aug 28, 2019 at 13:04
  • Right, but you can't define default values for members in an interface. You need to either create a class that implements the interface, which provides the default, or you need to provide the default values when instantiating the variable. Commented Aug 28, 2019 at 13:14

2 Answers 2

2

Use a class if you want to have a default value. Otherwise, do something like that:

sensorObject.sensor1 = [];
sensorObject.sensor2 = [];
Sign up to request clarification or add additional context in comments.

2 Comments

I am trying to prevent the use of Classes here. I was thinking the same about it as your second option but did not want to pollute the space I am declaring all attributes in. Guess I could also just put the instantiation in a function and call that before I need the variable.
You can do it as a one liner just like the other answer if you don't want a class but it gets annoying quickly if you have to build the whole object just to add default value every time you want to use it.
2

You can simply instantiate the object:

private sensorObject: objectWithSensors = {
  sensor1: [],
  sensor2: []
}

1 Comment

Trying to keep the space I use for declaring attributes as clean as possible. I just realized I could still use this technique by moving the instantiation to a function and call that before I use it.

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.