0

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.

1 Answer 1

1

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.

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

2 Comments

In your first case, why can't I do a push with just one of the values, the rest being set to null or whatever the defaults are. As in car.model.push({ year: '2002' }); ?
no1 said you can't, simply make model: [] if you want an empty array and push in it later on, I've just put something inside for the example or if you want empty values you can initialize it with all null values doesn't matter model: [ { color: null, type: null, year: null }] also works but I don't see why would you want null values if you can make it an empty array

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.