48

I have an object like so:

var obj = {
    key1: "apple",
    key2: true,
    key3: 123,
    .
    .
    .
    key{n}: ...
}

So obj can contain any number of named keys, but the values must all be either string, bool, or number.

How do I declare the type of obj as an interface in TypeScript? Can I declare an associative array (or variadic tuple) of a union type or something similar?

prmph
  • 7,616
  • 11
  • 37
  • 46

2 Answers2

83

Yes, you can use an index signature:

interface MyType {
    [key: string]: string | boolean | number;
}

var obj: MyType = {
    key1: "apple",
    key2: true,
    key3: 123
};
Scott Martin
  • 1,260
  • 2
  • 17
  • 27
David Sherret
  • 101,669
  • 28
  • 188
  • 178
  • 6
    Did you find this in the docs? I have searched (certainly not everything though …), to no avail. Link would be very much appreciated! – panepeter Dec 06 '18 at 12:49
3

I've dug deeper into the docs after reading this question and David's answer, and came up with a terrific solution!

I've used Generic Types to create a Dictionary Interface!

interface Dictionary<Type> {
   [key: string]: Type;
}

Which you can (re)use like so:

const myNumbers:Dictionary<number> = {
    key1: 1,
    key2: 2,
    key3: 3
};

const myStrings: Dictionary<string> = {
    key1: 'Lorem',
    key2: 'Ipsum',
    key3: 'Dolor'
};

const myElements:Dictionary<HTMLElement> = {
    button: document.querySelector('#button'),
    input: document.querySelector('#input')
};
Umur Karagöz
  • 2,970
  • 1
  • 19
  • 29