add new property in Typescript object

送分小仙女□ 提交于 2021-02-19 02:41:05

问题


I'm trying to add new property in object, but typescript given error.

error TS2339: Property 'qty' does not exist on type 'Object'.

product: Object = {qty: Number};

foo(){
  this.product.qty = 1;
}

回答1:


Object is the wrong annotation. Change your annotation:

product: {qty: number} = {qty: 0};

foo(){
  this.product.qty = 1;
}



回答2:


Number is a data type not a value. the object only accept the value not datatype. So you can't declare number as a value

try this simple way

product: any;

foo(){
  this.product.qty = 1;
}



回答3:


Seems that you've tried to do this:

product: {qty: number} = {};

foo(){
  this.product.qty = 1;
}

This won't work, although, because the object you've started with is incomplete. You should either mark the property as optional:

product: {qty?: number} = {};

foo(){
  this.product.qty = 1;
}

Or provide some default value:

product: {qty: number | null} = {qty: null};
// or just {qty: number}, if you don't use strict null checks

foo(){
  this.product.qty = 1;
}

If default value is a number too, you can even simplify this by using type inference:

product = {qty: 0};

foo(){
  this.product.qty = 1;
}

All these three examples will work (if you provide proper value for this in function foo, of course, but I assume that you'll do it anyway).




回答4:


Change Object to any type

product: any = {qty: Number};

foo(){
  this.product.qty = 1;
}



回答5:


Use this

product = {qty: null};

OR

product = {qty: 0};

instead of this -

product: Object = {qty: Number};

Because you initializing your object with key and value as type which is number so instead of assigning type you need to set some value which is anything say 0 or null or anything you want as the default value.




回答6:


You can also do like this and add as many as new properties you want in a product

product: Object = new Object();

foo(){
  this.product['qty'] = 1;
}


来源:https://stackoverflow.com/questions/51055405/add-new-property-in-typescript-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!