0

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
      }
    ]
  }

3 Answers 3

5

Another option is

const myFavs = {
   icecreams: [
     {
       name: 'Vanilla',
       sorbet: false
     },
     {
       name: 'Strawberry',
       sorbet: true
     }
   ] as Icecream[]
 }
Sign up to request clarification or add additional context in comments.

Comments

4

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
        }
    ]
}

Comments

1

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:)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.