简体   繁体   English

如何定义对象属性值的类型

[英]How to define the type for the value of an object property

In TypeScript I can declare a typed Array as follows:在 TypeScript 中,我可以声明一个类型化的数组,如下所示:

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.在这里,我不关心 propA、propB 等的名称,我不想要一个定义顶级属性名称的接口,但我确实想强制每个属性值都属于 Something 类型。 Is this possible?这可能吗? Thanks in advance.提前致谢。

You can use { [key: string]: Something } :您可以使用{ [key: string]: Something }

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

playground . 操场

@Psidom has answered correctly. @Psidom 已正确回答。 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.当您希望在另一个打字稿文件中使用相同的myJsonObject时,这可能会对您有所帮助。 You can add this interface in *.d.ts and export it and import it in any typescript file.您可以在*.d.ts添加此接口并将其导出并导入到任何打字稿文件中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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