How do I generate a index signature type with a number as key in TypeScript using quicktype?

617 views Asked by At

I am currently trying to create TypeScript interfaces with quicktype and am now facing the challenge of generating a variable with a index signature type with a number as key.

I already managed to generate a variable with a index signature type and a string as key. It seems like this is the default behaviour, because I did not define string as key type.

This is the json schema:

{
    "$id": "Test",
    "$schema": "http://json-schema.org/draft-07/schema#",
    "title": "Test",
    "definitions": {
        "A": {
            "type": "object",
            "properties": {
                "x": {
                    "type": "integer"
                }
            }
        }
    },
    "type": "object",
    "properties": {
        "mapA": {
            "type": "object",
            "additionalProperties": {
                "$ref": "#/definitions/A"
            }
        }
    },
    "required": [
        "mapA"
    ]
}

And these are the generated TypeScript interfaces:

export interface Test {
    mapA: { [key: string]: A };
}

export interface A {
    x?: number;
}

Can anybody tell me if it is possible to generate a index signature type with a number as key like this:

export interface Test {
    mapA: { [key: number]: A };
}

Thans for your help!

2

There are 2 answers

0
Urkallinger On BEST ANSWER

Official comment of quicktype team:

JSON does not allow number maps, so we cannot support it.

0
J. Doe On

Looks like a bug to me. If I test your expected TypeScript code (with number als index signature key) with source type "TypeScript" and target language "JSON Schema" quicktype makes an array instead of the map.

Tested here.