Reputation: 137
I would like to declare an object that has the following structure
public car = {
price: 20000,
currency: EUR,
seller: null,
model: {
color: null,
type: null,
year: null
} as Array<object>
};
Then, when I work with this object, I have something like
public addProduct(typeId: number): void {
this.car.model.push({type: typeId});
}
The problem I am facing is when I defined the model
object, as using as Array<object>
generates something alone the lines
Type '{ color: null; type: null; year: null; }' cannot be converted to type 'object[]'. Property 'length' is missing in type '{ color: null; type: null; year: null; }
I couldn't find a proper why to define this. It was important to use push
to generate an "empty" object to which I can add the attributes from the view.
Upvotes: 0
Views: 49
Reputation: 1468
You can create an object in typescript like
let car: any = {
price: 20000,
currency: 'EUR',
seller: null,
model: [
{ color: 'red', type: 'one', year: '2000' },
{ color: 'blue', type: 'two', year: '2001' }
]
}
Then you can do what you wanted
car.model.push({ color: 'green', type: 'three', year: '2002' });
to add a new model, or to fetch one
car.model[0] // returns { color: 'red', type: 'one', year: '2000' }
Another alternative would be to create a class instead of an object
export class Car {
public price: number;
public currency: string;
public seller: string;
public models: any[];
constructor() { }
}
And then put all the appropriate methods inside the class.
Upvotes: 1