簡體   English   中英

如何定義對象屬性值的類型

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

在 TypeScript 中,我可以聲明一個類型化的數組,如下所示:

interface Something {
  a: number,
  b: number
}

const arr: Array<Something> = [{a:1, b:2}, {a:3, b:4}]

但是我將如何聲明等效對象的類型:

const obj = {
  propA: {a:1, b:2},
  propB: {a:3, b:4}
}

在這里,我不關心 propA、propB 等的名稱,我不想要一個定義頂級屬性名稱的接口,但我確實想強制每個屬性值都屬於 Something 類型。 這可能嗎? 提前致謝。

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

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

操場

@Psidom 已正確回答。 歸功於他。 我只是回答,因為上面回答的代碼可以通過定義自定義對象的另一個接口來模塊化。

interface myJsonObject{
 [key: string] : Something
}

const obj: myJsonObject = {
 propsA : {a: 1, b:2},
 propsB : {a: 3, b:4}
}

當您希望在另一個打字稿文件中使用相同的myJsonObject時,這可能會對您有所幫助。 您可以在*.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