Reputation: 8246
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
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
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