Hoff
Hoff

Reputation: 39836

typescript syntax for declaring type inside object

I have an interface for icecream and it looks like so:

interface Icecream {
  name: string
  sorbet?: boolean
}

Now I want to create an object which contains a property icecreams, and I want that property to be an array of type Icecream. How can I tell Typescript that, since the colon : notation is already used for assignment?

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

Upvotes: 0

Views: 2728

Answers (3)

Hoff
Hoff

Reputation: 39836

I came across another way: add brackets around the key plus type, like so:

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

This seems to be the most concise and readable syntax so far, not sure when it was added to typescript or if has always been there:)

Upvotes: 1

user663031
user663031

Reputation:

Another option is

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

Upvotes: 5

Saravana
Saravana

Reputation: 40594

You type the myFavs variable:

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

Or use a type alias to make it more readable:

type objectWithIceCreamsArrayProperty = {
    icecreams: Icecream[]
}

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

Upvotes: 4

Related Questions