Interface for associative object array in TypeScript
Asked Answered
M

2

49

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?

Mcallister answered 5/7, 2016 at 22:35 Comment(0)
D
83

Yes, you can use an index signature:

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

var obj: MyType = {
    key1: "apple",
    key2: true,
    key3: 123
};
Dewberry answered 5/7, 2016 at 22:40 Comment(1)
Did you find this in the docs? I have searched (certainly not everything though …), to no avail. Link would be very much appreciated!Linehan
N
5

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')
};
Navarrette answered 11/8, 2022 at 20:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.