繁体   English   中英

你如何在打字稿中声明一个对象数组?

[英]how do you declare an array of objects inside typescript?

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

bagTotal = (products) => {
 // function does stuff
}

我知道我可以这样做:

bagTotal = (products: any[]) => {
 // function does stuff
}

但这比我想要的要轻松一些:严格使用打字稿。

products是一组外观相同的对象; 所有对象都有名称、价格和描述。

我怎么能声明呢?

我想做类似的事情

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”,这样您就可以声明一个 Product 数组,如下所示:

products: Product[];

并将其作为参数传递,如下所示:

bagTotal = (products: Product[]) => {
 // function does stuff
}

要上课,您可以使用以下代码创建一个 new.ts 文件:

export class Product {
  name: String;
  price: Number;
  description: String;
}

我希望这有帮助!

谢谢你。

通用数组类型Array<elemType>提供了一种简单的方法来声明对象数组:

bagTotal = (products: Array<{name: string, price: number}>) => {
   ...
}

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

class Item(){
    name: string;
    description: string;
    etc: any

  constructor() {
    this.name;
    this.description;
    this.etc;
}}

然后您可以将该数组指定为项目对象的数组:

itemArray: Array<Item>;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM