如何为格式 JSON 创建界面?

How to create interface for format JSON?

如何在 TypeScript 中为此模式创建接口 JSON:

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

我试过了:

interface IJson {
  number: number[]
}

看起来你需要一个 index signature 在这里,因为你想要一个具有任意数字键的类型。这样看起来像:

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 即可。

您可以使用字符串或数字作为键,也可以使用多种类型的映射值。

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

如果对数组的元素个数没有特殊要求,可以使用type IJSON = Record<string, number[]>Record 是 built-in 类型。