prmph
prmph

Reputation: 8246

Interface for associative object array in TypeScript

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?

Upvotes: 49

Views: 51214

Answers (2)

David Sherret
David Sherret

Reputation: 106880

Yes, you can use an index signature:

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

var obj: MyType = {
    key1: "apple",
    key2: true,
    key3: 123
};

Upvotes: 84

Umur Karagöz
Umur Karagöz

Reputation: 3200

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')
};

Upvotes: 5

Related Questions