Nathan Birrell

Define key types in Typescript interfaces

April 20, 2018

Use bracket notation to define key types on Typescript interfaces. This is useful on key-driven data structures.

For example, if we have an object of PositionErrors, where the key is our numeric error code and the value is an object with information about the error type.

interface IErrorType {
  [key:number]: {
    code: string,
    message: string
  }
}

// For example:
export const PositionError:IErrorType = {
  1: {
    code: 'PERMISSION_DENIED',
    message: 'Please allow permission'
  },
  2: {
    code: 'POSITION_UNAVAILABLE',
    message: 'Something went wrong :('
  }
}

Nathan Birrell

Software engineer, primarily focussed on Javascript web application development.
🇦🇺 Melbourne, Australia | Github | Linkedin | CV