简体   繁体   中英

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

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 .

@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}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM