用于在对象

时间:2017-05-09 12:23:21

标签: typescript type-declaration

我有一个冰淇淋界面,它看起来像这样:

interface Icecream {
  name: string
  sorbet?: boolean
}

现在我要创建一个包含属性 icecreams 的对象,我希望该属性为 Icecream类型的数组。我怎么能告诉Typescript,因为冒号:符号已用于赋值?

 const myFavs = {
    icecreams: [
      {
        name: 'Vanilla',
        sorbet: false
      },
      {
        name: 'Strawberry',
        sorbet: true
      }
    ]
  }

3 个答案:

答案 0 :(得分:2)

您输入myFavs变量:

const myFavs: {
     icecreams: Icecream[]
 } = {
    icecreams: [
      {
        name: 'Vanilla',
        sorbet: false
      },
      {
        name: 'Strawberry',
        sorbet: true
      }
    ]
  }

或使用类型别名使其更具可读性:

type objectWithIceCreamsArrayProperty = {
    icecreams: Icecream[]
}

const myFavs: objectWithIceCreamsArrayProperty = {
    icecreams: [
        {
            name: 'Vanilla',
            sorbet: false
        },
        {
            name: 'Strawberry',
            sorbet: true
        }
    ]
}

答案 1 :(得分:1)

另一种选择是

const myFavs = {
   icecreams: [
     {
       name: 'Vanilla',
       sorbet: false
     },
     {
       name: 'Strawberry',
       sorbet: true
     }
   ] as Icecream[]
 }

答案 2 :(得分:0)

我遇到了另一种方式:在键加类型周围添加括号,如下所示:

const myFavs = {
    [icecreams: Icecream[]]: [
      {
        name: 'Vanilla',
        sorbet: false
      },
      {
        name: 'Strawberry',
        sorbet: true
      }
    ]
  }

到目前为止,这似乎是最简洁和最易读的语法,不确定它何时被添加到typescript或者是否一直存在:)