Reputation: 57223
In TypeScript I can declare a typed Array as follows:
interface Something {
a: number,
b: number
}
const arr: Array<Something> = [{a:1, b:2}, {a:3, b:4}]
But how would I declare the type for the object equivalent:
const obj = {
propA: {a:1, b:2},
propB: {a:3, b:4}
}
Here, I don't care about the names of propA, propB, etc and I don't want an interface that defines the names of the top level properties but I do want to enforce that each property value is of type Something. Is this possible? Thanks in advance.
Upvotes: 3
Views: 669
Reputation: 6059
@Psidom has answered correctly. Credits to him. I am just answering because the above-answered code can be modularized by defining another interface of your custom object.
interface myJsonObject{
[key: string] : Something
}
const obj: myJsonObject = {
propsA : {a: 1, b:2},
propsB : {a: 3, b:4}
}
This might help you when you want the same myJsonObject
in another typescript file. You can add this interface in *.d.ts
and export it and import it in any typescript file.
//my.d.ts
interface Something {
a: number,
b: number
}
export interface myJsonObject {
[key: string] : Something
}
//any_typescript_file.ts
import { myJsonObject } from "./my.d.ts"
const obj: myJsonObject = {
propsA : {a: 1, b:2},
propsB : {a: 3, b:4}
}
Upvotes: 2
Reputation: 215117
You can use { [key: string]: Something }
:
const obj: { [key: string]: Something } = {
propA: {a:1, b:2},
propB: {a:3, b:4}
}
Upvotes: 4