bcherny / json-schema-to-typescript

Compile JSON Schema to TypeScript type declarations
https://bcherny.github.io/json-schema-to-typescript-browser/
MIT License
2.95k stars 392 forks source link

Add option to remove `[k: string]: unknown | undefined;` from generated types #572

Closed jahirfiquitiva closed 8 months ago

jahirfiquitiva commented 10 months ago

Hi

I would like to make the generated types a bit more strict by removing the types: [k: string]: unknown | undefined;

Is that possible? Otherwise, would you mind implementing such feature? Thanks in advance!

sudhanshug16 commented 9 months ago

I think you can use additionalProperties: false, to achieve this

jahirfiquitiva commented 9 months ago

I have it like that and it still generates them @sudhanshug16

sudhanshug16 commented 9 months ago

Maybe you have additionalProperties: true in your JSON schema.

If that's the case and you really don't want to have that generic signature in your types, you can set additionalProperties to false on all the nodes, I am using this:


export function setNoAdditionalProps(schema: SchemaObject) {
  if (schema.type === "object") {
    schema.additionalProperties = false;
    for (const [, value] of Object.entries(schema.properties ?? {})) {
      setNoAdditionalProps(value as SchemaObject);
    }
  }
  if (schema.type === "array") {
    setNoAdditionalProps(schema.items as SchemaObject);
  }
}
jahirfiquitiva commented 9 months ago

@sudhanshug16 oh that's right, I was trying to use the schema from https://github.com/jsonresume/resume-schema/blob/master/schema.json and it does have additionalProperties: true

I will try this function later and let you know. Thank you so much!

jahirfiquitiva commented 8 months ago

@sudhanshug16 sorry it took me so long to get back to this, but I wanted to let you know your setNoAdditionalProps function worked fine 🙌 Thanks for the help!