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?

2 Answers 2

84

Yes, you can use an index signature:

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

var obj: MyType = {
    key1: "apple",
    key2: true,
    key3: 123
};
Sign up to request clarification or add additional context in comments.

1 Comment

Did you find this in the docs? I have searched (certainly not everything though …), to no avail. Link would be very much appreciated!
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')
};

Comments

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.