Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/387.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在typescript中声明对象数组?_Javascript_Reactjs_Typescript - Fatal编程技术网

Javascript 如何在typescript中声明对象数组?

Javascript 如何在typescript中声明对象数组?,javascript,reactjs,typescript,Javascript,Reactjs,Typescript,我想指定一个将对象数组作为参数的函数,但我没有为对象定义特定的类型(一种“匿名类型”) 我明白我可以做到这一点: bagTotal = (products: any[]) => { // function does stuff } 但这比我想要的要轻松一点:严格使用typescript 产品是外观相同的对象的数组;所有对象都有名称、价格和说明 我如何申报 我想做一些像 bagTotal = (products: [{name: string, price: number, descri

我想指定一个将对象数组作为参数的函数,但我没有为对象定义特定的类型(一种“匿名类型”)

我明白我可以做到这一点:

bagTotal = (products: any[]) => {
 // function does stuff
}
但这比我想要的要轻松一点:严格使用typescript

产品
是外观相同的对象的数组;所有对象都有名称、价格和说明

我如何申报

我想做一些像

bagTotal = (products: [{name: string, price: number, description: string}]) => {
 // function does stuff
}

但这是不对的。我如何声明这一点?

你就快到了,括号的位置是错误的:

{name: string, price: number, description: string}[]
您使用它的方式并不是完全错误,但它意味着其他东西:它意味着一个数组,其中正好有一个此类项


我还建议将其提取到接口,这样可以使类型可重用,并且更易于阅读:

interface Product {
    name: string;
    price: number;
    description: string;
}

const products: Product[];

我认为必须声明类“Product”,这样才能声明如下所示的产品数组:

products: Product[];
bagTotal = (products: Product[]) => {
 // function does stuff
}
class Item(){
    name: string;
    description: string;
    etc: any

  constructor() {
    this.name;
    this.description;
    this.etc;
}}
并将其作为如下参数传递:

products: Product[];
bagTotal = (products: Product[]) => {
 // function does stuff
}
class Item(){
    name: string;
    description: string;
    etc: any

  constructor() {
    this.name;
    this.description;
    this.etc;
}}
要拥有该类,您可以使用以下代码创建一个新的.ts文件:

export class Product {
  name: String;
  price: Number;
  description: String;
}
我希望这有帮助


谢谢。

如果您要声明特定对象的数组,并希望为对象中的变量指定类型,我将为该对象创建一个类,如下所示:

products: Product[];
bagTotal = (products: Product[]) => {
 // function does stuff
}
class Item(){
    name: string;
    description: string;
    etc: any

  constructor() {
    this.name;
    this.description;
    this.etc;
}}
然后可以将该数组指定为项对象数组:

itemArray: Array<Item>;
itemArray:Array;

这里有一个使用-
数组声明它的清晰方法

bagTotal=(产品:数组)=>{
//函数确实有用
}

为什么你说它不对?如果项目类型非常大,我建议使用
数组
表单:
数组
我刚刚补充说我实际上会为它提取一个类型;)@IngoBürk我忽略了我的问题。请看。如果你回答这个问题,我可以接受你的回答,thanks@Red您界面中的Baron产品仍然是非类型化的,那么这有什么意义呢?而且我正在回滚该编辑。收到答案后,请不要从根本上改变问题。你问了一个问题,它已经被回答了。对于一个新问题,请打开一个新问题。好的,当它允许我也打开一个新问题时,我会接受这个问题。谢谢