Angular 2 Export Interface Initialize Inside Component Issue
I Am Having Kind of a Goofy Problem. Inside My Component I Export Some Interfaces and Whe I Try to Use Them Inside My Component If I Don't Initialize Them I Am...
i am having kind of a goofy problem. inside my component i export some interfaces and whe i try to use them inside my component if i dont initialize them i am geting issues about undifined which i totaly normal. Is these any other way to init them without writting all that code again?
export interface Data {
Code: string;
Date: Date;
OccurredDate: Date;
Person: Person;
Vehicle: Vehicle;
Policy: Policy;
OccurredLocation: OccurredLocation;
Phones: Phone[];
Notes: string;
Actions: Action[];
}
export interface RootObject {
Data: Data[];
IsSuccessful: boolean;
Messages: any[];
}
these are 2 of my interfaces and i init them like this:
export class SubscriberComponent {
public myRootObject: RootObject = {
Data: this.myData[0],
IsSuccessful: true,
Messages: null
}
public myData: Data ={
Code: '',
Date: new Date(),
OccurredDate: new Date(),
Person: null,
Vehicle: null,
Policy: null,
OccurredLocation: null,
Phones: null,
Notes: '',
Actions: null,
}
}
when i try to use myData.Code if i dont initialize it with '' i get and error. any other way to init my templates without all that much code?
1 Answer
The short answer of how to initialize an object of type Data would be:
myData = {} as Data;
But a bit more explanation... Interfaces are more of a "help" for the programmer himself, as well as the IDE, that can "warn" you with squiggly lines and errors that you are now assigning wrong type of values.
During runtime, this doesn't really matter though. Typescript is a superset of JavaScript, and TS will be compiled as JS during runtime, and in JS there are no interfaces.
To present this regarding interfaces, we could say we have an interface like so:
interface Foo {
bar: number
bas: string
}
and a object initialized like so: foo = {} as Foo;
Since using an Interface your IDE is helpful and warns you of assigning wrong type of data to foo.bar. BUT this would still run and assign the object to foo.bar:
this.foo.bar = { id:1, name: "name" };
So as mentioned on top of answer, if you do not need default values for your Data object, the proper way to initialize the object would be:
myData = {} as Data;
this will solve your undefined issue, since the object is initialized as an empty object. So unless you need default values, you can see it's pretty useless to initialize the properties, as the even the type of the properties can be overwritten.
Here's a sample of how you can overwrite a string value with an object just to have some reference on what I explained above :)