如何为格式json创建界面



如何在此模式JSON中创建输入字样:

{
  "1": [1,2,3],
  "55": [1,3,68]
}

我尝试了:

interface IJson {
  number: number[]
}

您可以拥有字符串或数字的键,也可以将映射的值也为几种类型。

interface IJSON {
    [key: string]: (string | number)[];
    [index: number]: (string | number)[];
}
const test: IJSON = {
    "1": [1, 2, 3],
    "55": [1, 3, 68],
    525: [1, 3, 68],
}

如果您想拥有更多通用的东西,则可以将通用的索引类型使用。

interface IJSON2<TValue> {
    [key: string]: TValue[];
    [index: number]: TValue[];
}
const test2: IJSON2<number> = {
    "1": [1, 2, 3],
    "55": [1, 3, 68]
}

看起来您需要在此处进行索引签名,因为您想要一种具有任意数字键的类型。所以看起来像:

interface IJson {
    [key: number]: number[];
}
// This assignment is okay:
const test: IJSON = {
    "1": [1, 2, 3],
    "55": [1, 3, 68],
}
// This is also okay and someValue is inferred to have type number[]
const someValue = test[1]
// But be careful, using this, only numbers can index the type:
// See the below note for how to allow string indices instead.
const otherValue = test["55"] // Error: Index expression is not of type number.

请注意,如果对用例更有效,则还可以使用索引签名的字符串而不是数字。只需将key: number替换为key: string

如果您对数组中元素的数量没有特殊要求,则可以使用type IJSON = Record<string, number[]>Record是一种内置类型。

最新更新