Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define the type for the value of an object property

Tags:

typescript

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.

like image 745
danday74 Avatar asked Oct 29 '25 08:10

danday74


1 Answers

You can use { [key: string]: Something }:

const obj: { [key: string]: Something } = {
  propA: {a:1, b:2},
  propB: {a:3, b:4}
}

playground.

like image 138
Psidom Avatar answered Nov 01 '25 00:11

Psidom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!