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.
You can use { [key: string]: Something }:
const obj: { [key: string]: Something } = {
propA: {a:1, b:2},
propB: {a:3, b:4}
}
playground.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With