0

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 !

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

It seems to work, but I've never seen the syntax [key: string] before. Don't you have a link for this ?
Updated the answer. Scroll down to Indexable Types

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.