HelloEdit
HelloEdit

Reputation: 74

Typescript object pattern?

I have just started TypeScript and I want to know how to declare an interface for this type of object:

const branch = {
  'CN': {
    'name': 'CN Name',
    'branch': 'Chinoise',
    'url': 'CN URL'
  },
  'DE': {
    'name': 'DE Name',
    'branch': 'Allemande',
    'discord': 'DE Discord',
    'url': 'DE URL'
  },
  'EN': {
    'name': 'EN Name',
    'branch': 'Anglaise',
    'url': 'EN URL'
  },
  [...]
}

As you can see, I've got this interface:

interface Branch {
    name: string,
    branch: string,
    discord?: string,
    url: string
}

Repeated several times in the above code. So I wanted to know if it was possible to say to TypeScript:"Hey, the Branch object contains this interface which is repeated many times".

Thanks !

Upvotes: 0

Views: 446

Answers (1)

guramidev
guramidev

Reputation: 2238

You can do it like this:

const branch: {[key: string]: Branch} = ...;

Which means that branch variable is an object whose keys are of type string and values are of type Branch;

Official Docs for index signatures: https://www.typescriptlang.org/docs/handbook/interfaces.html

Upvotes: 2

Related Questions